Android Http协议笔记(使用HttpURLConnection)文件上传+参数

代码地址:http://download.csdn.NET/detail/u013063185/8892951


1.Android网络请求数据是最常用,最近在研究Http网络请求,来记一下笔记

 

下面的博客是Http协议的解析,我就不重复了:

http://blog.csdn.net/gueter/article/details/1524447

 

2.下面是Http 请求的一个例子:

客户端:

GET http://www.hstc.edu.cn/turbosearch/search_new.htm HTTP/1.1

Host: www.hstc.edu.cn

Connection: keep-alive

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 UBrowser/5.1.2238.18 Safari/537.36

Referer: http://www.hstc.edu.cn/2013/

Accept-Encoding: gzip, deflate

Accept-Language: zh-CN,zh;q=0.8

Cookie: _gscu_538514159=347153715akloz45; ASPSESSIONIDCQSDSSQS=LCEPCIJAFOEJOCKJPDPBNJME

 

服务器端

HTTP/1.1 200 OK

Content-Length: 397

Content-Type: text/html

Last-Modified: Wed, 09 Jan 2013 02:04:00 GMT

Accept-Ranges: bytes

ETag: "3655d97deecd1:83c0"

Server: YxlinkWAF        

X-Powered-By: ASP.Net

Date: Sun, 12 Jul 2015 05:24:01 GMT

 

<html>

。。。

</html>

 

 

3.关于安卓HTTP请求用HttpUrlConnection还是HttpClient好http://blog.csdn.NET/huzgd/article/details/8712187

 

下面就进入主题,使用Android的HttpUrlConnection写网络请求,代码比较简单,直接上


[java]  view plain  copy
  1. package com.ptwyj.http;  
  2.   
  3. import java.io.ByteArrayOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.net.HttpURLConnection;  
  9. import java.net.MalformedURLException;  
  10. import java.net.ProtocolException;  
  11. import java.net.URL;  
  12. import java.net.URLEncoder;  
  13. import java.util.Map;  
  14.   
  15. import android.content.Context;  
  16. import android.util.Log;  
  17. import android.widget.Toast;  
  18.   
  19. public class HttpUtil {  
  20.   
  21.     public final static String TAG = "HTTP";  
  22.     private final static int CONNECT_TIME = 10000;  
  23.     private final static int READ_TIME = 10000;  
  24.   
  25.     /** 
  26.      * 发送post请求 
  27.      *  
  28.      * @param path 
  29.      * @param map 
  30.      * @param string 
  31.      * @return 
  32.      * @throws IOException 
  33.      */  
  34.     public String doPost(String urlstr, Map<String, String> map, String encoding)  
  35.             throws IOException {  
  36.   
  37.         StringBuilder data = new StringBuilder();  
  38.         // 数据拼接 key=value&key=value  
  39.         if (map != null && !map.isEmpty()) {  
  40.             for (Map.Entry<String, String> entry : map.entrySet()) {  
  41.                 data.append(entry.getKey()).append("=");  
  42.                 data.append(URLEncoder.encode(entry.getValue(), encoding));  
  43.                 data.append("&");  
  44.             }  
  45.             data.deleteCharAt(data.length() - 1);  
  46.         }  
  47.   
  48.         Log.i(TAG, data.toString());  
  49.         byte[] entity = data.toString().getBytes();// 生成实体数据  
  50.         URL url = new URL(urlstr);  
  51.         HttpURLConnection connection = getHttpURLConnection(urlstr, "POST");  
  52.   
  53.         connection.setDoOutput(true);// 允许对外输出数据  
  54.   
  55.         connection.setRequestProperty("Content-Length",  
  56.                 String.valueOf(entity.length));  
  57.   
  58.         OutputStream outStream = connection.getOutputStream();  
  59.         outStream.write(entity);  
  60.         if (connection.getResponseCode() == 200) {// 成功返回处理数据  
  61.             InputStream inStream = connection.getInputStream();  
  62.             byte[] number = read(inStream);  
  63.             String json = new String(number);  
  64.             return json;  
  65.         }  
  66.   
  67.         return null;  
  68.   
  69.     }  
  70.   
  71.     public String doPost(String urlstr) throws IOException {  
  72.         return doPost(urlstr, null"UTF-8");  
  73.     }  
  74.   
  75.     public String doPost(String urlstr, Map<String, String> map)  
  76.             throws IOException {  
  77.         return doPost(urlstr, map, "UTF-8");  
  78.     }  
  79.   
  80.     /** 
  81.      * 发送GET请求 
  82.      *  
  83.      * @param id 
  84.      * @return 
  85.      * @throws IOException 
  86.      * @throws Exception 
  87.      */  
  88.     public String doGet(String urlstr) throws Exception {  
  89.         HttpURLConnection connection = getHttpURLConnection(urlstr, "GET");  
  90.   
  91.         if (connection.getResponseCode() == 200) {  
  92.             InputStream inStream = connection.getInputStream();  
  93.             byte[] number = read(inStream);  
  94.             String json = new String(number);  
  95.             return json;  
  96.         }  
  97.         return null;  
  98.     }  
  99.   
  100.     private HttpURLConnection getHttpURLConnection(String urlstr, String method)  
  101.             throws IOException {  
  102.         URL url = new URL(urlstr);  
  103.         HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  104.         connection.setConnectTimeout(CONNECT_TIME);  
  105.         connection.setReadTimeout(READ_TIME);  
  106.         connection.setRequestMethod(method);  
  107.   
  108.         // 头字段  
  109.         connection.setRequestProperty("Accept""*/*");  
  110.         connection.setRequestProperty("Accept-Charset""UTF-8,*;q=0.5");  
  111.         connection.setRequestProperty("Accept-Encoding""gzip,deflate");  
  112.         connection.setRequestProperty("Accept-Language""zh-CN");  
  113.         connection.setRequestProperty("User-Agent""Android WYJ");  
  114.         connection.setRequestProperty("Content-Type",  
  115.                 "application/x-www-form-urlencoded");// 头字段  
  116.   
  117.         return connection;  
  118.   
  119.     }  
  120.   
  121.     /**  
  122.      * 读取输入流数据 InputStream  
  123.      *   
  124.      * @param inStream  
  125.      * @return  
  126.      * @throws IOException  
  127.      */  
  128.     public static byte[] read(InputStream inStream) throws IOException {  
  129.         ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
  130.         byte[] buffer = new byte[1024];  
  131.         int len = 0;  
  132.         while ((len = inStream.read(buffer)) != -1) {  
  133.             outStream.write(buffer, 0, len);  
  134.         }  
  135.         inStream.close();  
  136.         return outStream.toByteArray();  
  137.     }  
  138. }  


Http协议的Content-Type有3种,经常使用的有multipart/form-data和application/x-www-form-urlencoded(默认),multipart/form-data方式可以上传文件,下面我增加了一个同时可以上传图片jpg和参数的方法:


[java]  view plain  copy
  1. /** 
  2.      * 发送文件post请求 
  3.      *  
  4.      * @param path 
  5.      * @param map 
  6.      * @param string 
  7.      * @return 
  8.      * @throws IOException 
  9.      */  
  10.     public String doFilePost(String urlstr, Map<String, String> map,  
  11.             Map<String, File> files) throws IOException {  
  12.         String BOUNDARY = "----WebKitFormBoundaryDwvXSRMl0TBsL6kW"// 定义数据分隔线  
  13.   
  14.         URL url = new URL(urlstr);  
  15.         HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
  16.         // 发送POST请求必须设置如下两行  
  17.         connection.setDoOutput(true);  
  18.         connection.setDoInput(true);  
  19.         connection.setUseCaches(false);  
  20.         connection.setRequestMethod("POST");  
  21.         connection.setRequestProperty("Accept""*/*");  
  22.         connection.setRequestProperty("connection""Keep-Alive");  
  23.         connection.setRequestProperty("user-agent""Android WYJ");  
  24.         connection.setRequestProperty("Charsert""UTF-8");  
  25.         connection.setRequestProperty("Accept-Encoding""gzip,deflate");  
  26.         connection.setRequestProperty("Content-Type",  
  27.                 "multipart/form-data; boundary=" + BOUNDARY);  
  28.   
  29.         OutputStream out = new DataOutputStream(connection.getOutputStream());  
  30.         byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线  
  31.   
  32.         // 文件  
  33.         if (files != null && !files.isEmpty()) {  
  34.             for (Map.Entry<String, File> entry : files.entrySet()) {  
  35.                 File file = entry.getValue();  
  36.                 String fileName = entry.getKey();  
  37.   
  38.                 StringBuilder sb = new StringBuilder();  
  39.                 sb.append("--");  
  40.                 sb.append(BOUNDARY);  
  41.                 sb.append("\r\n");  
  42.                 sb.append("Content-Disposition: form-data;name=\"" + fileName  
  43.                         + "\";filename=\"" + file.getName() + "\"\r\n");  
  44.                 sb.append("Content-Type: image/jpg\r\n\r\n");  
  45.                 byte[] data = sb.toString().getBytes();  
  46.                 out.write(data);  
  47.   
  48.                 DataInputStream in = new DataInputStream(new FileInputStream(  
  49.                         file));  
  50.                 int bytes = 0;  
  51.                 byte[] bufferOut = new byte[1024];  
  52.                 while ((bytes = in.read(bufferOut)) != -1) {  
  53.                     out.write(bufferOut, 0, bytes);  
  54.                 }  
  55.                 out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个  
  56.                 in.close();  
  57.             }  
  58.         }  
  59.         // 数据参数  
  60.         if (map != null && !map.isEmpty()) {  
  61.   
  62.             for (Map.Entry<String, String> entry : map.entrySet()) {  
  63.                 StringBuilder sb = new StringBuilder();  
  64.                 sb.append("--");  
  65.                 sb.append(BOUNDARY);  
  66.                 sb.append("\r\n");  
  67.                 sb.append("Content-Disposition: form-data; name=\""  
  68.                         + entry.getKey() + "\"");  
  69.                 sb.append("\r\n");  
  70.                 sb.append("\r\n");  
  71.                 sb.append(entry.getValue());  
  72.                 sb.append("\r\n");  
  73.                 byte[] data = sb.toString().getBytes();  
  74.                 out.write(data);  
  75.             }  
  76.         }  
  77.         out.write(end_data);  
  78.         out.flush();  
  79.         out.close();  
  80.   
  81.         // 定义BufferedReader输入流来读取URL的响应  
  82. //      BufferedReader reader = new BufferedReader(new InputStreamReader(  
  83. //              connection.getInputStream()));  
  84. //      String line = null;  
  85. //      while ((line = reader.readLine()) != null) {  
  86. //          System.out.println(line);  
  87. //      }  
  88.   
  89.         if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {  
  90.             InputStream inStream = connection.getInputStream();  
  91.             byte[] number = read(inStream);  
  92.             String json = new String(number);  
  93.             return json;  
  94.         }  
  95.           
  96.         return null;  
  97.     }  

代码地址:http://download.csdn.net/detail/u013063185/8892951

Fiddler.exe网络抓包工具,android也可以使用,很强大

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值