Android Http 助手类(麻雀虽小),实现文件上/传下载,Cookie机制
来源:互联网 发布:信越7783硅脂淘宝 编辑:程序博客网 时间:2024/04/29 04:44
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);//formdatafor (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());}//filesint 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);
- Android Http 助手类(麻雀虽小),实现文件上/传下载,Cookie机制
- Android 系统上实现APK插件机制——360手机助手
- Android 系统上实现APK插件机制——360手机助手
- Android端实现Cookie机制
- Http Cookie机制及Cookie的实现原理
- 30.gitHub开源xUtils工具实现断电续传下载
- Android上实现Http请求
- 【HTTP】Cookie/Session机制详解
- Http Cookie/Session机制详解
- HTTP Session、Cookie机制详解
- cookie实现session机制
- Android http请求类添加Cookie
- Android HTTP session && cookie
- Delphi + IIS + VbScript(*.asp) 实现多线上传下载和软件自动更新.
- FTPClient断点传下载,在Android端在通知栏显示进度
- Angular最佳实践之$http-麻雀虽小 五脏俱全
- android手机助手拷贝文件至pc上失败的解决方式
- http-客户端识别与cookie机制
- 回车和换行
- windows远程连接Ubuntu14.04—vnc4server
- JAVA CAS实现原理与使用
- 在来电监听服务中动态注册去电广播(BroadcastRecevier)
- runtime基础教程(1)-OC元素认知
- Android Http 助手类(麻雀虽小),实现文件上/传下载,Cookie机制
- 判断是否有某个class
- AFHTTPSessionManager
- 开始学前端,从行元素和块元素区别开始(第一篇)
- MYSQL where 1=1 的作用
- 两段相同打印正三角形代码,为啥结果不同啊?请帮忙看下哪里有问题呢?
- jQuery form插件之ajaxForm()和ajaxSubmit()的可选参数项对象
- Spring Boot 填坑日志
- 第一次写博客 呵呵