歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android入門:封裝一個HTTP請求的輔助類

Android入門:封裝一個HTTP請求的輔助類

日期:2017/3/1 10:15:56   编辑:Linux編程

前面的文章中,我們曾經實現了一個HTTP的GET 和 POST 請求(見 http://www.linuxidc.com/Linux/2012-07/66006.htm );此處我封裝了一個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

  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

  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. }

測試代碼:

  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);

文件上傳測試代碼:

  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);

簡單了很多,對吧?

Copyright © Linux教程網 All Rights Reserved