前面的文章中,我们曾经实现了一个HTTP的GET 和 POST 请求;

此处我封装了一个HTTP的get和post的辅助类,能够更好的使用;

类名:HttpRequestUtil

提供了如下功能:

(1)模拟GET请求;

(2)模拟POST请求;

(3)模拟文件上传请求;

(4)发送XML数据;

发送GET请求


(1)public static URLConnection sendGetRequest(String url, Map<String, String> params, Map<String, String> headers)

参数:

(1)url:单纯的URL,不带任何参数;

(2)params:参数;

(3)headers:需要设置的HTTP请求头;

返回:

HttpURLConnection

发送POST请求


(2)public static URLConnection sendPostRequest(String url, Map<String, String> params, Map<String, String> headers)

参数:

(1)url:单纯的URL,不带任何参数;

(2)params:参数;

(3)headers:需要设置的HTTP请求头;

返回:

HttpURLConnection

文件上传


(3)public static boolean uploadFiles(String url, Map<String, String> params, FormFile[] files)

参数:

(1)url:单纯URL

(2)params:参数;

(3)files:多个文件

返回:是否上传成功

(4)public static boolean uploadFile(String path, Map<String, String> params, FormFile file)

参数:

(1)url:单纯URL

(2)params:参数;

(3)file:一个文件

返回:是否上传成功

发送XML数据


(5)public static byte[] postXml(String url, String xml, String encoding)

参数:

(1)url:单纯URL

(2)xml:XML数据

(3)XML数据编码

对于上传文件,FormFile的构造函数声明如下:

(1)public FormFile(String filname, byte[] data, String parameterName, String contentType)

参数:

(1)filname:文件的名称

(2)data:文件的数据

(3)parameterName:HTML的文件上传控件的参数的名字

(4)contentType:文件类型,比如text/plain为txt

(2)public FormFile(String filname, File file, String parameterName, String contentType)

参数:

(1)filname:文件的名称

(2)file:文件名

(3)parameterName:HTML的文件上传控件的参数的名字

(4)contentType:文件类型,比如text/plain为txt

FormFile.java

[java] view
plain
copy

  1. package com.xiazdong.netword.http.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.io.FileNotFoundException;
  5. import java.io.InputStream;
  6. /**
  7. * 上传文件
  8. */
  9. public class FormFile {
  10. /* 上传文件的数据 */
  11. private byte[] data;
  12. private InputStream inStream;
  13. private File file;
  14. /* 文件名称 */
  15. private String filname;
  16. /* 请求参数名称*/
  17. private String parameterName;
  18. /* 内容类型 */
  19. private String contentType = "application/octet-stream";
  20. /**
  21. * 此函数用来传输小文件
  22. * @param filname
  23. * @param data
  24. * @param parameterName
  25. * @param contentType
  26. */
  27. public FormFile(String filname, byte[] data, String parameterName, String contentType) {
  28. this.data = data;
  29. this.filname = filname;
  30. this.parameterName = parameterName;
  31. if(contentType!=null) this.contentType = contentType;
  32. }
  33. /**
  34. * 此函数用来传输大文件
  35. * @param filname
  36. * @param file
  37. * @param parameterName
  38. * @param contentType
  39. */
  40. public FormFile(String filname, File file, String parameterName, String contentType) {
  41. this.filname = filname;
  42. this.parameterName = parameterName;
  43. this.file = file;
  44. try {
  45. this.inStream = new FileInputStream(file);
  46. } catch (FileNotFoundException e) {
  47. e.printStackTrace();
  48. }
  49. if(contentType!=null) this.contentType = contentType;
  50. }
  51. public File getFile() {
  52. return file;
  53. }
  54. public InputStream getInStream() {
  55. return inStream;
  56. }
  57. public byte[] getData() {
  58. return data;
  59. }
  60. public String getFilname() {
  61. return filname;
  62. }
  63. public void setFilname(String filname) {
  64. this.filname = filname;
  65. }
  66. public String getParameterName() {
  67. return parameterName;
  68. }
  69. public void setParameterName(String parameterName) {
  70. this.parameterName = parameterName;
  71. }
  72. public String getContentType() {
  73. return contentType;
  74. }
  75. public void setContentType(String contentType) {
  76. this.contentType = contentType;
  77. }
  78. }

HttpRequestUtil.java

[java] view
plain
copy

  1. package com.xiazdong.netword.http.util;
  2. import java.io.BufferedReader;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.InputStream;
  8. import java.io.InputStreamReader;
  9. import java.io.OutputStream;
  10. import java.net.HttpURLConnection;
  11. import java.net.InetAddress;
  12. import java.net.Socket;
  13. import java.net.URL;
  14. import java.net.URLConnection;
  15. import java.net.URLEncoder;
  16. import java.util.HashMap;
  17. import java.util.Map;
  18. import java.util.Map.Entry;
  19. import java.util.Set;
  20. /*
  21. * 此类用来发送HTTP请求
  22. * */
  23. public class HttpRequestUtil {
  24. /**
  25. * 发送GET请求
  26. * @param url
  27. * @param params
  28. * @param headers
  29. * @return
  30. * @throws Exception
  31. */
  32. public static URLConnection sendGetRequest(String url,
  33. Map<String, String> params, Map<String, String> headers)
  34. throws Exception {
  35. StringBuilder buf = new StringBuilder(url);
  36. Set<Entry<String, String>> entrys = null;
  37. // 如果是GET请求,则请求参数在URL中
  38. if (params != null && !params.isEmpty()) {
  39. buf.append("?");
  40. entrys = params.entrySet();
  41. for (Map.Entry<String, String> entry : entrys) {
  42. buf.append(entry.getKey()).append("=")
  43. .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
  44. .append("&");
  45. }
  46. buf.deleteCharAt(buf.length() - 1);
  47. }
  48. URL url1 = new URL(buf.toString());
  49. HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
  50. conn.setRequestMethod("GET");
  51. // 设置请求头
  52. if (headers != null && !headers.isEmpty()) {
  53. entrys = headers.entrySet();
  54. for (Map.Entry<String, String> entry : entrys) {
  55. conn.setRequestProperty(entry.getKey(), entry.getValue());
  56. }
  57. }
  58. conn.getResponseCode();
  59. return conn;
  60. }
  61. /**
  62. * 发送POST请求
  63. * @param url
  64. * @param params
  65. * @param headers
  66. * @return
  67. * @throws Exception
  68. */
  69. public static URLConnection sendPostRequest(String url,
  70. Map<String, String> params, Map<String, String> headers)
  71. throws Exception {
  72. StringBuilder buf = new StringBuilder();
  73. Set<Entry<String, String>> entrys = null;
  74. // 如果存在参数,则放在HTTP请求体,形如name=aaa&age=10
  75. if (params != null && !params.isEmpty()) {
  76. entrys = params.entrySet();
  77. for (Map.Entry<String, String> entry : entrys) {
  78. buf.append(entry.getKey()).append("=")
  79. .append(URLEncoder.encode(entry.getValue(), "UTF-8"))
  80. .append("&");
  81. }
  82. buf.deleteCharAt(buf.length() - 1);
  83. }
  84. URL url1 = new URL(url);
  85. HttpURLConnection conn = (HttpURLConnection) url1.openConnection();
  86. conn.setRequestMethod("POST");
  87. conn.setDoOutput(true);
  88. OutputStream out = conn.getOutputStream();
  89. out.write(buf.toString().getBytes("UTF-8"));
  90. if (headers != null && !headers.isEmpty()) {
  91. entrys = headers.entrySet();
  92. for (Map.Entry<String, String> entry : entrys) {
  93. conn.setRequestProperty(entry.getKey(), entry.getValue());
  94. }
  95. }
  96. conn.getResponseCode(); // 为了发送成功
  97. return conn;
  98. }
  99. /**
  100. * 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
  101. *   <FORM METHOD=POST ACTION="http://192.168.0.200:8080/ssi/fileload/test.do" enctype="multipart/form-data">
  102. <INPUT TYPE="text" NAME="name">
  103. <INPUT TYPE="text" NAME="id">
  104. <input type="file" name="imagefile"/>
  105. <input type="file" name="zip"/>
  106. </FORM>
  107. * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
  108. * @param params 请求参数 key为参数名,value为参数值
  109. * @param file 上传文件
  110. */
  111. public static boolean uploadFiles(String path, Map<String, String> params, FormFile[] files) throws Exception{
  112. final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
  113. final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志
  114. int fileDataLength = 0;
  115. if(files!=null&&files.length!=0){
  116. for(FormFile uploadFile : files){//得到文件类型数据的总长度
  117. StringBuilder fileExplain = new StringBuilder();
  118. fileExplain.append("--");
  119. fileExplain.append(BOUNDARY);
  120. fileExplain.append("\r\n");
  121. fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
  122. fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
  123. fileExplain.append("\r\n");
  124. fileDataLength += fileExplain.length();
  125. if(uploadFile.getInStream()!=null){
  126. fileDataLength += uploadFile.getFile().length();
  127. }else{
  128. fileDataLength += uploadFile.getData().length;
  129. }
  130. }
  131. }
  132. StringBuilder textEntity = new StringBuilder();
  133. if(params!=null&&!params.isEmpty()){
  134. for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据
  135. textEntity.append("--");
  136. textEntity.append(BOUNDARY);
  137. textEntity.append("\r\n");
  138. textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
  139. textEntity.append(entry.getValue());
  140. textEntity.append("\r\n");
  141. }
  142. }
  143. //计算传输给服务器的实体数据总长度
  144. int dataLength = textEntity.toString().getBytes().length + fileDataLength +  endline.getBytes().length;
  145. URL url = new URL(path);
  146. int port = url.getPort()==-1 ? 80 : url.getPort();
  147. Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
  148. OutputStream outStream = socket.getOutputStream();
  149. //下面完成HTTP请求头的发送
  150. String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
  151. outStream.write(requestmethod.getBytes());
  152. String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
  153. outStream.write(accept.getBytes());
  154. String language = "Accept-Language: zh-CN\r\n";
  155. outStream.write(language.getBytes());
  156. String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
  157. outStream.write(contenttype.getBytes());
  158. String contentlength = "Content-Length: "+ dataLength + "\r\n";
  159. outStream.write(contentlength.getBytes());
  160. String alive = "Connection: Keep-Alive\r\n";
  161. outStream.write(alive.getBytes());
  162. String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
  163. outStream.write(host.getBytes());
  164. //写完HTTP请求头后根据HTTP协议再写一个回车换行
  165. outStream.write("\r\n".getBytes());
  166. //把所有文本类型的实体数据发送出来
  167. outStream.write(textEntity.toString().getBytes());
  168. //把所有文件类型的实体数据发送出来
  169. if(files!=null&&files.length!=0){
  170. for(FormFile uploadFile : files){
  171. StringBuilder fileEntity = new StringBuilder();
  172. fileEntity.append("--");
  173. fileEntity.append(BOUNDARY);
  174. fileEntity.append("\r\n");
  175. fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
  176. fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
  177. outStream.write(fileEntity.toString().getBytes());
  178. if(uploadFile.getInStream()!=null){
  179. byte[] buffer = new byte[1024];
  180. int len = 0;
  181. while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
  182. outStream.write(buffer, 0, len);
  183. }
  184. uploadFile.getInStream().close();
  185. }else{
  186. outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
  187. }
  188. outStream.write("\r\n".getBytes());
  189. }
  190. }
  191. //下面发送数据结束标志,表示数据已经结束
  192. outStream.write(endline.getBytes());
  193. BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  194. if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
  195. return false;
  196. }
  197. outStream.flush();
  198. outStream.close();
  199. reader.close();
  200. socket.close();
  201. return true;
  202. }
  203. /**
  204. * 提交数据到服务器
  205. * @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
  206. * @param params 请求参数 key为参数名,value为参数值
  207. * @param file 上传文件
  208. */
  209. public static boolean uploadFile(String path, Map<String, String> params, FormFile file) throws Exception{
  210. return uploadFiles(path, params, new FormFile[]{file});
  211. }
  212. /**
  213. * 将输入流转为字节数组
  214. * @param inStream
  215. * @return
  216. * @throws Exception
  217. */
  218. public static byte[] read2Byte(InputStream inStream)throws Exception{
  219. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  220. byte[] buffer = new byte[1024];
  221. int len = 0;
  222. while( (len = inStream.read(buffer)) !=-1 ){
  223. outSteam.write(buffer, 0, len);
  224. }
  225. outSteam.close();
  226. inStream.close();
  227. return outSteam.toByteArray();
  228. }
  229. /**
  230. * 将输入流转为字符串
  231. * @param inStream
  232. * @return
  233. * @throws Exception
  234. */
  235. public static String read2String(InputStream inStream)throws Exception{
  236. ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
  237. byte[] buffer = new byte[1024];
  238. int len = 0;
  239. while( (len = inStream.read(buffer)) !=-1 ){
  240. outSteam.write(buffer, 0, len);
  241. }
  242. outSteam.close();
  243. inStream.close();
  244. return new String(outSteam.toByteArray(),"UTF-8");
  245. }
  246. /**
  247. * 发送xml数据
  248. * @param path 请求地址
  249. * @param xml xml数据
  250. * @param encoding 编码
  251. * @return
  252. * @throws Exception
  253. */
  254. public static byte[] postXml(String path, String xml, String encoding) throws Exception{
  255. byte[] data = xml.getBytes(encoding);
  256. URL url = new URL(path);
  257. HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  258. conn.setRequestMethod("POST");
  259. conn.setDoOutput(true);
  260. conn.setRequestProperty("Content-Type", "text/xml; charset="+ encoding);
  261. conn.setRequestProperty("Content-Length", String.valueOf(data.length));
  262. conn.setConnectTimeout(5 * 1000);
  263. OutputStream outStream = conn.getOutputStream();
  264. outStream.write(data);
  265. outStream.flush();
  266. outStream.close();
  267. if(conn.getResponseCode()==200){
  268. return read2Byte(conn.getInputStream());
  269. }
  270. return null;
  271. }
  272. //测试函数
  273. public static void main(String args[]) throws Exception {
  274. Map<String, String> params = new HashMap<String, String>();
  275. params.put("name", "xiazdong");
  276. params.put("age", "10");
  277. HttpURLConnection conn = (HttpURLConnection) HttpRequestUtil
  278. .sendGetRequest(
  279. "http://192.168.0.103:8080/Server/PrintServlet",
  280. params, null);
  281. int code = conn.getResponseCode();
  282. InputStream in = conn.getInputStream();
  283. byte[]data = read2Byte(in);
  284. }
  285. }

测试代码:

[java] view
plain
copy

  1. Map<String,String> params = new HashMap<String,String>();
  2. params.put("name", name.getText().toString());
  3. params.put("age", age.getText().toString());
  4. HttpURLConnection conn = (HttpURLConnection) HttpRequestUtil.sendGetRequest("http://192.168.0.103:8080/Server/PrintServlet", params, null);

文件上传测试代码:

[java] view
plain
copy

  1. FormFile formFile = new FormFile(file.getName(), file, "document", "text/plain");
  2. boolean isSuccess = HttpRequestUtil.uploadFile("http://192.168.0.103:8080/Server/FileServlet", null, formFile);

原文地址:点击打开链接

最新文章

  1. bzoj 2141: 排队
  2. Java环境变量的简记
  3. 硬件初始化,nand flash固化操作,系统启动简单流程
  4. Java 组播
  5. webconfig和appconfig中出现特殊字符如何处理
  6. Makefile选项CFLAGS,LDFLAGS,LIBS
  7. Qt 读取txt文件乱码的解决办法
  8. CSS学习------之简单图片切换
  9. [RxJS] Combination operators: concat, startWith
  10. 重复记录(duplicate records)相关运营数据
  11. jquery的几种异步请求,ajax
  12. 动态规划——min/max的单调性优化总结
  13. UVA 11478 Halum (差分约束)
  14. API和DLL
  15. Java Web相关问题
  16. java web 读取数据库数据写入Excel返回浏览器下载
  17. Linux 查找文件内容、替换
  18. docker实战练习(一)
  19. Sagas模式
  20. 教你摆脱低级程序猿 项目中cocopads的安装使用

热门文章

  1. 关于web中注册倒数的问题(亲测)
  2. Activity---弹出右侧窗口
  3. Material使用04 MdCardModule和MdButtonModule综合运用
  4. AngularJS中的DI
  5. 项目一:第五天 1、区域数据(pinyin4j-简码,城市编码) 2、Web层代码重构(model对象,分页代码提取) 3、区域分页查询 3、分区添加功能 4、定区管理管理-添加,分页
  6. Entity Framework Code-First(9.9):DataAnnotations - ForeignKey Attribute
  7. Spring入门第四课
  8. 25. CTF综合靶机渗透(17)
  9. 20169201 实验三 敏捷开发与XP实践报告
  10. [CentOS7] parted用于磁盘分区(同时支持GPT和MBR分区表)