【原創】一個android訪問http資源的便捷工具類——HttpHelper

來源:互聯網
上載者:User

HttpHelper.java

package com.newcj.net;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.UnsupportedEncodingException;import java.net.*;import org.apache.http.util.ByteArrayBuffer;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Handler;import android.util.Log;/** * 協助你訪問 http 資源的工具類 *  * @author <a href="mailto:newcj@qq.com">newcj</a> * @version 1.0 2010/5/9 */public final class HttpHelper {public final static String TAG = "HttpHelper";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";/** * 1024 byte */private final static int BUFFER_LENGTH = 1024;private String referer;private Cookies cookies;private int timeout = 300000;public HttpHelper() {cookies = new Cookies();}/** * 擷取逾時時間,毫秒單位,預設為300000毫秒即5分鐘 *  * @return */public int getTimeout() {return timeout;}/** * 設定逾時時間 ReadTimeOut 與 ConnectTimeout 均設定為該逾時時間,毫秒單位 *  * @param timeout */public void setTimeout(int timeout) {this.timeout = timeout;}/** * 擷取 Referer *  * @return */public String getReferer() {return referer;}/** * 設定 Referer *  * @return */public void setReferer(String referer) {this.referer = referer;}/** * 以GET方法建立一個線程擷取網頁,編碼方式為 gb2312,逾時或編碼錯誤返回null *  * @param strUrl *            網頁URL地址 * @param handler *            用於向發起本次調用的線程發送結果資訊 * @param what *            handler中的what標記 */public void getHtmlByThread(String strUrl, Handler handler, int what) {getHtmlByThread(strUrl, null, false, "gb2312", handler, what);}/** * 以GET方法建立一個線程擷取網頁,逾時或編碼錯誤返回null *  * @param strUrl *            網頁URL地址 * @param encoding *            編碼方式 * @param handler *            用於向發起本次調用的線程發送結果資訊 * @param what *            handler中的what標記 */public void getHtmlByThread(String strUrl, String encoding,Handler handler, int what) {getHtmlByThread(strUrl, null, false, encoding, handler, what);}/** * 根據GET或POST方法建立一個線程擷取網頁,逾時返回null *  * @param strUrl *            網頁URL地址 * @param strPost *            POST 的資料 * @param isPost *            是否 POST,true 則為POST ,false 則為 GET * @param encoding *            編碼方式 * @param handler *            用於向發起本次調用的線程發送結果資訊 * @param what *            handler中的what標記 */public void getHtmlByThread(String strUrl, String strPost, boolean isPost,String encoding, Handler handler, int what) {if (handler == null)throw new NullPointerException("handler is null.");Thread t = new Thread(new Runner(strUrl, strPost, isPost, encoding,handler, what, Runner.TYPE_HTML));t.setDaemon(true);t.start();}/** * 以GET方法擷取網頁,編碼方式為 gb2312,逾時或編碼錯誤返回null *  * @param strUrl *            網頁URL地址 * @return 返回網頁的字串 */public String getHtml(String strUrl) {return getHtml(strUrl, null, false, "gb2312");}/** * 以GET方法擷取網頁,逾時或編碼錯誤返回null *  * @param strUrl *            網頁URL地址 * @param encoding *            編碼方式 * @return 返回網頁的字串 */public String getHtml(String strUrl, String encoding) {return getHtml(strUrl, null, false, encoding);}/** * 根據GET或POST方法擷取網頁,逾時返回null *  * @param strUrl *            網頁URL地址 * @param strPost *            POST 的資料 * @param isPost *            是否 POST,true 則為POST ,false 則為 GET * @param encoding *            編碼方式 * @return 返回網頁的字串 */public String getHtml(String strUrl, String strPost, boolean isPost,String encoding) {String ret = null;try {byte[] data = getHtmlBytes(strUrl, strPost, isPost, encoding);if (data != null)ret = new String(data, encoding);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch block}return ret;}/** * 根據GET或POST方法擷取網路資料,逾時返回null *  * @param strUrl *            網頁URL地址 * @param strPost *            POST 的資料 * @param isPost *            是否POST,true則為POST,false則為 GET * @param encoding *            編碼方式 * @return 返回bytes */public byte[] getHtmlBytes(String strUrl, String strPost, boolean isPost,String encoding) {byte[] ret = null;HttpURLConnection httpCon = null;InputStream is = null;try {URL url = new URL(strUrl);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", cookies.toString());if (isPost) {httpCon.setDoOutput(true);httpCon.setRequestMethod("POST");httpCon.connect();OutputStream os = null;try {os = httpCon.getOutputStream();os.write(URLEncoder.encode(strPost, encoding).getBytes());os.flush();} finally {if (os != null)os.close();}}// 擷取資料is = httpCon.getInputStream();ByteArrayBuffer baBuffer = null;byte[] buffer = new byte[BUFFER_LENGTH];int rNum = 0;// 若讀取的資料長度小於 BUFFER_LENGTH,說明讀取的// 內容小於 BUFFER_LENGTH 已經一次性讀取完畢// 這個時候並不用建立 ByteArrayBuffer//// 以上並不適用// if ((rNum = is.read(buffer)) < BUFFER_LENGTH) {// ret = buffer;// } else {baBuffer = new ByteArrayBuffer(BUFFER_LENGTH << 1);// baBuffer.append(buffer, 0, BUFFER_LENGTH);while ((rNum = is.read(buffer)) != -1) {baBuffer.append(buffer, 0, rNum);}ret = baBuffer.toByteArray();// }} catch (Exception e) {// TODO Auto-generated catch blockLog.e(TAG, e.getMessage() + ":" + e.getCause());} finally {if (is != null) {try {is.close();} catch (IOException e) {// TODO Auto-generated catch block}}// 更新 Cookieif (httpCon != null) {cookies.putCookies(httpCon.getHeaderField("Set-Cookie"));// 更新 refererreferer = strUrl;httpCon.disconnect();}}return ret;}/** * 建立一個線程擷取一張網頁圖片 *  * @param strUrl * @param handler *            用於向發起本次調用的線程發送結果資訊 * @param what *            handler中的what標記 */public void getBitmapByThread(String strUrl, Handler handler, int what) {if (handler == null)throw new NullPointerException("handler is null.");Thread t = new Thread(new Runner(strUrl, null, false, null, handler,what, Runner.TYPE_IMG));t.setDaemon(true);t.start();}/** * 擷取一張網頁圖片 *  * @param strUrl *            網頁圖片的URL地址 * @return */public Bitmap getBitmap(String strUrl) {byte[] data = getHtmlBytes(strUrl, null, false, null);return BitmapFactory.decodeByteArray(data, 0, data.length);}private class Runner implements Runnable {public final static int TYPE_HTML = 1;public final static int TYPE_IMG = 2;private String strUrl;private String strPost;private boolean isPost;private String encoding;private Handler handler;private int what;private int type;public Runner(String strUrl, String strPost, boolean isPost,String encoding, Handler handler, int what, int type) {this.strUrl = strUrl;this.strPost = strPost;this.isPost = isPost;this.encoding = encoding;this.handler = handler;this.what = what;this.type = type;}@Overridepublic void run() {// TODO Auto-generated method stubObject obj = null;switch (type) {case TYPE_HTML:obj = getHtml(strUrl, strPost, isPost, encoding);break;case TYPE_IMG:obj = getBitmap(strUrl);break;}synchronized (handler) {handler.sendMessage(handler.obtainMessage(what, obj));}}}}

Cookies.java

package com.newcj.net;import java.util.HashMap;import java.util.Map.Entry;import java.util.Set;/** * 非同步儲存Cookie的索引值 *  * @author SomeWind *  */public class Cookies {private HashMap<String, String> hashMap;public Cookies() {hashMap = new HashMap<String, String>();}/** * 清除 Cookies 裡面的所有 Cookie 記錄 */public void clear() {hashMap.clear();}/** * 根據 key 擷取對應的 Cookie 值 *  * @param key *            要擷取的 Cookie 值的 key * @return 如果不存在 key 則返回 null */public String getCookie(String key) {return hashMap.get(key);}/** * 在 Cookies 裡設定一個 Cookie *  * @param key *            要設定的 Cookie 的 key * @param value *            要設定的 Cookie 的 value */public void putCookie(String key, String value) {hashMap.put(key, value);}/** * 在 Cookies 裡面設定傳入的 cookies *  * @param cookies */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) == '=') {this.putCookie(strCookies[i].substring(0, j),strCookies[i].substring(j + 1,strCookies[i].length()));}}}}/** * 擷取 Cookies 的字串 */@Overridepublic String toString() {// TODO Auto-generated method stubif (hashMap.isEmpty())return "";Set<Entry<String, String>> set = hashMap.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();}}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.