代码地址: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写网络请求,代码比较简单,直接上
- package com.ptwyj.http;
-
- import java.io.ByteArrayOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.UnsupportedEncodingException;
- import java.net.HttpURLConnection;
- import java.net.MalformedURLException;
- import java.net.ProtocolException;
- import java.net.URL;
- import java.net.URLEncoder;
- import java.util.Map;
-
- import android.content.Context;
- import android.util.Log;
- import android.widget.Toast;
-
- public class HttpUtil {
-
- public final static String TAG = "HTTP";
- private final static int CONNECT_TIME = 10000;
- private final static int READ_TIME = 10000;
-
-
-
-
-
-
-
-
-
-
- public String doPost(String urlstr, Map<String, String> map, String encoding)
- throws IOException {
-
- StringBuilder data = new StringBuilder();
-
- if (map != null && !map.isEmpty()) {
- for (Map.Entry<String, String> entry : map.entrySet()) {
- data.append(entry.getKey()).append("=");
- data.append(URLEncoder.encode(entry.getValue(), encoding));
- data.append("&");
- }
- data.deleteCharAt(data.length() - 1);
- }
-
- Log.i(TAG, data.toString());
- byte[] entity = data.toString().getBytes();
- URL url = new URL(urlstr);
- HttpURLConnection connection = getHttpURLConnection(urlstr, "POST");
-
- connection.setDoOutput(true);
-
- connection.setRequestProperty("Content-Length",
- String.valueOf(entity.length));
-
- OutputStream outStream = connection.getOutputStream();
- outStream.write(entity);
- if (connection.getResponseCode() == 200) {
- InputStream inStream = connection.getInputStream();
- byte[] number = read(inStream);
- String json = new String(number);
- return json;
- }
-
- return null;
-
- }
-
- public String doPost(String urlstr) throws IOException {
- return doPost(urlstr, null, "UTF-8");
- }
-
- public String doPost(String urlstr, Map<String, String> map)
- throws IOException {
- return doPost(urlstr, map, "UTF-8");
- }
-
-
-
-
-
-
-
-
-
- public String doGet(String urlstr) throws Exception {
- HttpURLConnection connection = getHttpURLConnection(urlstr, "GET");
-
- if (connection.getResponseCode() == 200) {
- InputStream inStream = connection.getInputStream();
- byte[] number = read(inStream);
- String json = new String(number);
- return json;
- }
- return null;
- }
-
- private HttpURLConnection getHttpURLConnection(String urlstr, String method)
- throws IOException {
- URL url = new URL(urlstr);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setConnectTimeout(CONNECT_TIME);
- connection.setReadTimeout(READ_TIME);
- connection.setRequestMethod(method);
-
-
- connection.setRequestProperty("Accept", "*/*");
- connection.setRequestProperty("Accept-Charset", "UTF-8,*;q=0.5");
- connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
- connection.setRequestProperty("Accept-Language", "zh-CN");
- connection.setRequestProperty("User-Agent", "Android WYJ");
- connection.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
-
- return connection;
-
- }
-
- /**
- * 读取输入流数据 InputStream
- *
- * @param inStream
- * @return
- * @throws IOException
- */
- public static byte[] read(InputStream inStream) throws IOException {
- ByteArrayOutputStream outStream = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = 0;
- while ((len = inStream.read(buffer)) != -1) {
- outStream.write(buffer, 0, len);
- }
- inStream.close();
- return outStream.toByteArray();
- }
- }
Http协议的Content-Type有3种,经常使用的有multipart/form-data和application/x-www-form-urlencoded(默认),multipart/form-data方式可以上传文件,下面我增加了一个同时可以上传图片jpg和参数的方法:
-
-
-
-
-
-
-
-
-
- public String doFilePost(String urlstr, Map<String, String> map,
- Map<String, File> files) throws IOException {
- String BOUNDARY = "----WebKitFormBoundaryDwvXSRMl0TBsL6kW";
-
- URL url = new URL(urlstr);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
-
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- connection.setRequestMethod("POST");
- connection.setRequestProperty("Accept", "*/*");
- connection.setRequestProperty("connection", "Keep-Alive");
- connection.setRequestProperty("user-agent", "Android WYJ");
- connection.setRequestProperty("Charsert", "UTF-8");
- connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
- connection.setRequestProperty("Content-Type",
- "multipart/form-data; boundary=" + BOUNDARY);
-
- OutputStream out = new DataOutputStream(connection.getOutputStream());
- byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();
-
-
- if (files != null && !files.isEmpty()) {
- for (Map.Entry<String, File> entry : files.entrySet()) {
- File file = entry.getValue();
- String fileName = entry.getKey();
-
- StringBuilder sb = new StringBuilder();
- sb.append("--");
- sb.append(BOUNDARY);
- sb.append("\r\n");
- sb.append("Content-Disposition: form-data;name=\"" + fileName
- + "\";filename=\"" + file.getName() + "\"\r\n");
- sb.append("Content-Type: image/jpg\r\n\r\n");
- byte[] data = sb.toString().getBytes();
- out.write(data);
-
- DataInputStream in = new DataInputStream(new FileInputStream(
- file));
- int bytes = 0;
- byte[] bufferOut = new byte[1024];
- while ((bytes = in.read(bufferOut)) != -1) {
- out.write(bufferOut, 0, bytes);
- }
- out.write("\r\n".getBytes());
- in.close();
- }
- }
-
- if (map != null && !map.isEmpty()) {
-
- for (Map.Entry<String, String> entry : map.entrySet()) {
- StringBuilder sb = new StringBuilder();
- sb.append("--");
- sb.append(BOUNDARY);
- sb.append("\r\n");
- sb.append("Content-Disposition: form-data; name=\""
- + entry.getKey() + "\"");
- sb.append("\r\n");
- sb.append("\r\n");
- sb.append(entry.getValue());
- sb.append("\r\n");
- byte[] data = sb.toString().getBytes();
- out.write(data);
- }
- }
- out.write(end_data);
- out.flush();
- out.close();
-
-
-
-
-
-
-
-
-
- if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
- InputStream inStream = connection.getInputStream();
- byte[] number = read(inStream);
- String json = new String(number);
- return json;
- }
-
- return null;
- }
代码地址:http://download.csdn.net/detail/u013063185/8892951
Fiddler.exe网络抓包工具,Android也可以使用,很强大
里面有web服务,加不多讲了,里面使用Handler进行异步封装,有兴趣可以学习交流一下。