zoukankan      html  css  js  c++  java
  • Android入门:封装一个HTTP请求的辅助类

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

    HttpRequestUtil.java

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



    测试代码:

    [java] view plaincopy
    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 plaincopy
    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);  

    原文地址:点击打开链接
  • 相关阅读:
    事件(五):事件委托
    事件(四):事件类型
    【[ZJOI2005]午餐】
    【[POI2006]OKR-Periods of Words】
    【2^k进制数】
    【[SHOI2015]脑洞治疗仪】
    【[NOI2016]区间】
    【[SHOI2014]概率充电器】
    【逛公园】
    【[CQOI2014]数三角形】
  • 原文地址:https://www.cnblogs.com/sowhat4999/p/4439867.html
Copyright © 2011-2022 走看看