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写网络请求,代码比较简单,直接上


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;

	/**
	 * 发送post请求
	 * 
	 * @param path
	 * @param map
	 * @param string
	 * @return
	 * @throws IOException
	 */
	public String doPost(String urlstr, Map<String, String> map, String encoding)
			throws IOException {

		StringBuilder data = new StringBuilder();
		// 数据拼接 key=value&key=value
		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");
	}

	/**
	 * 发送GET请求
	 * 
	 * @param id
	 * @return
	 * @throws IOException
	 * @throws Exception
	 */
	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和参数的方法:


/**
	 * 发送文件post请求
	 * 
	 * @param path
	 * @param map
	 * @param string
	 * @return
	 * @throws IOException
	 */
	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();
		// 发送POST请求必须设置如下两行
		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();

		// 定义BufferedReader输入流来读取URL的响应
//		BufferedReader reader = new BufferedReader(new InputStreamReader(
//				connection.getInputStream()));
//		String line = null;
//		while ((line = reader.readLine()) != null) {
//			System.out.println(line);
//		}

		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进行异步封装,有兴趣可以学习交流一下。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值