Android Http 助手类(麻雀虽小),实现文件上/传下载,Cookie机制

Android的学习快一段时间了,不知道以后用不用的得上,用了一晚时间集自己风格封装的Http助手类,未经过实战检验,自我测试通过,功能一般凑合着用吧。

感觉不如自己封的.net的http助手类强大(毕竟.net自己本来就有不少API,呵呵),使用的事HttpURLConnection,据说是Android上推荐的类额

贴上源码,基本常用功能都实现了额,转载注明额呵呵

package com.android.pblib;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.*;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.util.ByteArrayBuffer;

import com.java.pblib.UtilsStream;
import com.third.pblib.UtilsJodaTime;

import android.graphics.Color;
import android.util.Log;

public class UtilsHttpHelper {

	public final static String TAG = "MyHttpHelper";
	private final static String CONTENT_TYPE = "application/x-www-form-urlencoded";
	private final static String ACCEPT = "*/*";
	private final static String USER_AGENT = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1) Gecko/20090624 Firefox/3.5";

	private final static int BUFFER_LENGTH = 1024;
	private String referer;
	private Map<String, String> cookieMap;
	private int timeout = 300000;
	private String encoding = "utf-8";

	public UtilsHttpHelper() {
		cookieMap = new HashMap<String, String>();
	}

	String getCookie() {
		if (cookieMap.isEmpty())
			return "";

		Set<Entry<String, String>> set = cookieMap.entrySet();
		StringBuilder sb = new StringBuilder(set.size() * 50);
		for (Entry<String, String> entry : set) {
			sb.append(String.format("%s=%s;", entry.getKey(), entry.getValue()));
		}
		sb.delete(sb.length() - 1, sb.length());
		return sb.toString();
	}

	public void putCookies(String cookies) {
		if (cookies == null)
			return;

		String[] strCookies = cookies.split(";");
		for (int i = 0; i < strCookies.length; i++) {
			for (int j = 0; j < strCookies[i].length(); j++) {
				if (strCookies[i].charAt(j) == '=') {
					putCookie(strCookies[i].substring(0, j), strCookies[i].substring(j + 1, strCookies[i].length()));
				}
			}
		}
	}

	public void putCookie(String key, String value) {
		cookieMap.put(key, value);
	}

	HttpURLConnection getHttpResponse(String strUrl, String strPost, String method, String encoding) throws Exception {
		URL url = new URL(strUrl);
		HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
		httpCon.setReadTimeout(timeout);
		httpCon.setConnectTimeout(timeout);
		httpCon.setUseCaches(false);
		//httpCon.setInstanceFollowRedirects(true);
		//httpCon.setRequestProperty("Referer", referer);
		httpCon.setRequestProperty("Content-Type", CONTENT_TYPE);
		httpCon.setRequestProperty("Accept", ACCEPT);
		httpCon.setRequestProperty("User-Agent", USER_AGENT);
		httpCon.setRequestProperty("Cookie", getCookie());
		httpCon.setRequestProperty("Connection", "Keep-Alive");

		if (method.equals("POST")) {

			httpCon.setDoOutput(true);
			httpCon.setDoInput(true);
			httpCon.setRequestMethod("POST");

			OutputStream os = httpCon.getOutputStream();
			os.write(strPost.getBytes(Charset.forName(encoding)));
			os.flush();
			os.close();
		}
		// 获取数据
		return httpCon;
	}

	byte[] getRemoteBytes(String strUrl, String strPost, String method, String encoding) throws Exception {
		byte[] ret = null;
		InputStream is = null;
		HttpURLConnection httpCon = null;
		try {
			httpCon = getHttpResponse(strUrl, strPost, method, encoding);
			is = httpCon.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[BUFFER_LENGTH];
			int n = 0;
			while ((n = is.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}
			ret = out.toByteArray();
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			if (httpCon != null) {
				putCookies(httpCon.getHeaderField("Set-Cookie"));
				// 更新 referer
				//referer = strUrl;
				httpCon.disconnect();
			}
		}
		return ret;
	}

	public String get(String strUrl) throws Exception {
		byte[] buff = getRemoteBytes(strUrl, null, "GET", encoding);
		return new String(buff, Charset.forName(encoding));
	}

	public String post(String strUrl, String postdata) throws Exception {
		byte[] buff = getRemoteBytes(strUrl, postdata, "POST", encoding);
		return new String(buff, Charset.forName(encoding));
	}

	public void downfile(String strUrl, String strPost, String method, File file) throws Exception {
		byte[] ret = null;
		InputStream is = null;
		HttpURLConnection httpCon = null;

		httpCon = getHttpResponse(strUrl, strPost, method, encoding);
		is = httpCon.getInputStream();
		UtilsStream.InputStreamToFile(is, file);
	}

	public void downfile(String strUrl, File file) throws Exception {
		byte[] ret = null;
		InputStream is = null;
		HttpURLConnection httpCon = null;

		httpCon = getHttpResponse(strUrl, "", "POST", encoding);
		is = httpCon.getInputStream();
		UtilsStream.InputStreamToFile(is, file);
	}

	HttpURLConnection submitform(String strUrl, Map<String, String> data, Map<String, InputStream> files) throws Exception {
		String BOUNDARY = UUID.randomUUID().toString();
		String CONTENT_TYPE = "multipart/form-data"; //内容类型
		String PREFIX = "--", LINE_END = "\r\n";

		String __BOUNDARY = "--" + BOUNDARY + "\r\n"; //数据分隔线  
		String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志  

		URL url = new URL(strUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(10 * 10000000);
		conn.setConnectTimeout(10 * 10000000);
		conn.setDoInput(true);//允许输入流  
		conn.setDoOutput(true);//允许输出流  
		conn.setUseCaches(false);//不允许使用缓存   
		conn.setRequestMethod("POST");//请求方式   
		conn.setRequestProperty("Charset", encoding);//设置编码
		conn.setRequestProperty("Connection", "keep-alive");
		conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
		conn.setRequestProperty("Cookie", "now=" + UtilsJodaTime.Format(new Date(), "yyyyMMddHHmmss") + ";");
		OutputStream outputSteam = conn.getOutputStream();
		DataOutputStream dos = new DataOutputStream(outputSteam);

		//formdata
		for (Entry<String, String> entry : data.entrySet()) {
			StringBuffer sb = new StringBuffer();
			//键值对一
			sb.append(__BOUNDARY);
			sb.append("Content-Disposition: form-data;name=\"" + entry.getKey() + "\"\r\n\r\n" + entry.getValue() + "" + LINE_END);
			dos.write(sb.toString().getBytes());
		}
		//files
		int index = 0;
		for (Entry<String, InputStream> entry : files.entrySet()) {
			index++;
			String filekey = String.format("uploadfile%d", index);
			//文件一
			StringBuffer sb = new StringBuffer();
			sb.append(__BOUNDARY);
			sb.append("Content-Disposition: form-data; name=\"" + filekey + "\"; filename=\"" + entry.getKey() + "\"" + LINE_END);
			sb.append("Content-Type: application/octet-stream; charset=" + encoding + LINE_END);
			sb.append(LINE_END);
			dos.write(sb.toString().getBytes());

			InputStream is = entry.getValue();
			byte[] bytes = new byte[1024];
			int len = 0;
			while ((len = is.read(bytes)) != -1) {
				dos.write(bytes, 0, len);
			}
			is.close();
			dos.write(LINE_END.getBytes());
		}
		dos.write(endline.getBytes());
		dos.flush();
		return conn;
	}

	public String submitformWidthResult(String strUrl, Map<String, String> data, Map<String, InputStream> files) throws Exception {
		byte[] ret = null;
		InputStream is = null;
		HttpURLConnection httpCon = null;
		try {
			httpCon = submitform(strUrl, data, files);
			is = httpCon.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[BUFFER_LENGTH];
			int n = 0;
			while ((n = is.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}
			ret = out.toByteArray();
			return new String(ret, Charset.forName(encoding));
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (Exception e) {
				// TODO: handle exception
			}
			if (httpCon != null) {
				putCookies(httpCon.getHeaderField("Set-Cookie"));
				// 更新 referer
				//referer = strUrl;
				httpCon.disconnect();
			}
		}
	}

}

使用方法那是Easyway

UtilsHttpHelper helper = new UtilsHttpHelper();

//GET请求

String res=helper.get(testURL);

//POST请求

String res=helper.post(testURL, "abc=ddd&kkk=fff");


//文件下载

helper.downfile(downURL, new File(Environment.getExternalStorageDirectory().toString()+"/download/123456.jpg"))


//提交Form,且带文件上传

Map<String, String> datas = new HashMap<String, String>();
datas.put("abc", "ogeg");
datas.put("ert", "gg");
Map<String, InputStream> files = new HashMap<String, InputStream>();
files.put("abc", self.getResources().getAssets().open("test.jpg"));
String result = helper.submitformWidthResult(testURL, datas, files);


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值