Java 利用HttpURLConnection发送http请求
2016-04-05 09:42
686 查看
写了一个简单的 Http 请求的Class,实现了 get, post ,postfile
package com.asus.uts.util; import org.json.JSONException; import org.json.JSONObject; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; /** * Created by jiezhou on 16/2/22. */ public class HttpHelper { public static void main(String[] args) throws JSONException{ JSONObject json = new JSONObject(); json.put("un", "bruce"); json.put("pwd", "123456"); //get request r = get("http://127.0.0.1:5000/index/user/1/m", json); System.out.println(r.status_code); System.out.println(r.text); //post json data String s = "{'sex': 'm', 'name': '', 'id': 1}"; JSONObject json2 = new JSONObject(s); request r2 = post("http://127.0.0.1:5000/index/user/1/m", json2);
//post File String path = "/Users/jiezhou/Documents/test.py"; postFile("http://127.0.0.1:5000/fileupload", "temp.txt", "/Users/jiezhou/Documents/temp.txt"); } /** * 请求返回的对象 * @author jiezhou * */ public static class request{ //状态码 public int status_code; //返回数据 public String text; } private HttpHelper(){ } /** * 从服务器get 数据 * @param getUrl URL地址 * @param params JSONObject类型的数据格式 * @return request */ public static request get(String getUrl, JSONObject params){ request r = new request(); HttpURLConnection conn = null; try { //拼接参数 if (params != null) { String per = null; for (int i=0; i< params.names().length(); i++){ per = i == 0? "?" : "&"; getUrl += per + params.names().get(i).toString() + "=" + params.get(params.names().get(i).toString()); } } URL url = new URL(getUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(10000); int status_code = conn.getResponseCode(); r.status_code = status_code; if (status_code == 200){ InputStream is = conn.getInputStream(); r.text = getStringFromInputStream(is); } } catch (Exception e) { } return r; } /** * post 数据 * @param getUrl URL地址 * @param params JSONObject类型的数据格式 * @return request */ public static request post(String getUrl, JSONObject params){ request r = new request(); HttpURLConnection conn = null; try { URL url = new URL(getUrl); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setReadTimeout(5000); conn.setConnectTimeout(10000); conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容 // post请求的参数 String data = null; //拼接参数 if (params != null) { data = params.toString(); } // 获得一个输出流,向服务器写数据,默认情况下,系统不允许向服务器输出内容 OutputStream out = conn.getOutputStream();// 获得一个输出流,向服务器写数据 out.write(data.getBytes()); out.flush(); out.close(); int status_code = conn.getResponseCode(); r.status_code = status_code; if (status_code == 200){ InputStream is = conn.getInputStream(); r.text = getStringFromInputStream(is); } } catch (Exception e) { System.out.println(e.getMessage().toString()); } return r; } /** * post上传文件 * @param getUrl url 地址 * @param fileName 文件名 * @param filePath 文件路径 * @return request */ public static request postFile(String getUrl, String fileName, String filePath){ request r = new request(); HttpURLConnection conn = null; try { String end = "\r\n"; String twoHyphens = "--"; String boundary = "******"; // 定义数据分隔线 URL url = new URL(getUrl); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true);// 设置此方法,允许向服务器输出内容 conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setReadTimeout(5000); conn.setConnectTimeout(10000); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // post请求的参数 DataOutputStream ds = new DataOutputStream(conn.getOutputStream()); ds.writeBytes(twoHyphens + boundary + end); ds.writeBytes("Content-Disposition: form-data; " + "name=\"file\";filename=\"" + fileName + "\"" + end); ds.writeBytes(end); /* 取得文件的FileInputStream */ FileInputStream fStream = new FileInputStream(filePath); /* 设置每次写入1024bytes */ int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; int length = -1; /* 从文件读取数据至缓冲区 */ while ((length = fStream.read(buffer)) != -1) { /* 将资料写入DataOutputStream中 */ ds.write(buffer, 0, length); } ds.writeBytes(end); ds.writeBytes(twoHyphens + boundary + twoHyphens + end); /* close streams */ fStream.close(); ds.flush(); int status_code = conn.getResponseCode(); r.status_code = status_code; if (status_code == 200){ InputStream is = conn.getInputStream(); r.text = getStringFromInputStream(is); } } catch (Exception e) { System.out.println(e.getMessage().toString()); } return r; } /** * 装换InputStream * @param is * @return * @throws IOException */ private static String getStringFromInputStream(InputStream is) throws IOException { ByteArrayOutputStream os = new ByteArrayOutputStream(); // 模板代码 必须熟练 byte[] buffer = new byte[1024]; int len = -1; // 一定要写len=is.read(buffer) // 如果while((is.read(buffer))!=-1)则无法将数据写入buffer中 while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } is.close(); String state = os.toString();// 把流中的数据转换成字符串,采用的编码是utf-8(模拟器默认编码) os.close(); return state; } }
相关文章推荐
- iperf+sed+gnuplotting查看无线网络速度
- HTTP协议详解
- Linux C高级编程——网络编程之UDP(4)
- Linux C高级编程——网络编程之TCP(3)
- Python自动化测试 (九)urllib2 发送HTTP Request
- tcp三次握手四次挥手详解
- hdu4292Food【拆点网络流】
- 神经网络梯度下降的三种学习方式
- C#获取本机上所有网络接口及真实IP地址信息
- C# HttpWebRequest 绝技 根据URL地址获取网页信息
- UniversalAndroidImageLoader出现异常:ImageLoader: Unable to resolve host "https": No address associated with host
- 管理聚合链路和桥接网络(多网卡绑定,redhat liunx 7.0) 基础知识
- Tomcat处理HTTP请求源码分析
- 详解https是如何确保安全的?
- BFA“瑞云科技”大视频讲堂第4期“网络视频成就影视梦想”
- 20159318 《网络攻击与防范》第5周学习总结
- Flex HTTPService
- Flex HTTPService
- win8无线网络不稳定怎么办?win8无线网络不稳定解决方法
- 与HTTP协作的Web服务器——代理、网关、隧道