一个android访问http资源的便捷工具类——HttpHelper
HttpHelper.java
1 package com.whizen.servicedemo.util; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.io.UnsupportedEncodingException; 7 import java.net.*; 8 import org.apache.http.util.ByteArrayBuffer; 9 10 import android.graphics.Bitmap; 11 import android.graphics.BitmapFactory; 12 import android.os.Handler; 13 import android.util.Log; 14 15 /** 16 * 帮助你访问 http 资源的工具类 17 * 18 * @author 19 * @version 1.0 20 */ 21 public final class HttpHelper { 22 public final static String TAG = "HttpHelper"; 23 24 private final static String CONTENT_TYPE = "application/x-www-form-urlencoded"; 25 private final static String ACCEPT = "*/*"; 26 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"; 27 28 /** 29 * 1024 byte 30 */ 31 private final static int BUFFER_LENGTH = 1024; 32 33 private String referer; 34 private Cookies cookies; 35 private int timeout = 300000; 36 37 public HttpHelper() { 38 cookies = new Cookies(); 39 } 40 41 /** 42 * 获取超时时间,毫秒单位,默认为300000毫秒即5分钟 43 * 44 * @return 45 */ 46 public int getTimeout() { 47 return timeout; 48 } 49 50 /** 51 * 设置超时时间 ReadTimeOut 与 ConnectTimeout 均设置为该超时时间,毫秒单位 52 * 53 * @param timeout 54 */ 55 public void setTimeout(int timeout) { 56 this.timeout = timeout; 57 } 58 59 /** 60 * 获取 Referer 61 * 62 * @return 63 */ 64 public String getReferer() { 65 return referer; 66 } 67 68 /** 69 * 设置 Referer 70 * 71 * @return 72 */ 73 public void setReferer(String referer) { 74 this.referer = referer; 75 } 76 77 /** 78 * 以GET方法新建一个线程获取网页,编码方式为 gb2312,超时或编码错误返回null 79 * 80 * @param strUrl 81 * 网页URL地址 82 * @param handler 83 * 用于向发起本次调用的线程发送结果信息 84 * @param what 85 * handler中的what标记 86 */ 87 public void getHtmlByThread(String strUrl, Handler handler, int what) { 88 getHtmlByThread(strUrl, null, false, "gb2312", handler, what); 89 } 90 91 /** 92 * 以GET方法新建一个线程获取网页,超时或编码错误返回null 93 * 94 * @param strUrl 95 * 网页URL地址 96 * @param encoding 97 * 编码方式 98 * @param handler 99 * 用于向发起本次调用的线程发送结果信息 100 * @param what 101 * handler中的what标记 102 */ 103 public void getHtmlByThread(String strUrl, String encoding, Handler handler, int what) { 104 getHtmlByThread(strUrl, null, false, encoding, handler, what); 105 } 106 107 /** 108 * 根据GET或POST方法新建一个线程获取网页,超时返回null 109 * 110 * @param strUrl 111 * 网页URL地址 112 * @param strPost 113 * POST 的数据 114 * @param isPost 115 * 是否 POST,true 则为POST ,false 则为 GET 116 * @param encoding 117 * 编码方式 118 * @param handler 119 * 用于向发起本次调用的线程发送结果信息 120 * @param what 121 * handler中的what标记 122 */ 123 public void getHtmlByThread(String strUrl, String strPost, boolean isPost, String encoding, 124 Handler handler, int what) { 125 if (handler == null) 126 throw new NullPointerException("handler is null."); 127 128 Thread t = new Thread(new Runner(strUrl, strPost, isPost, encoding, handler, what, 129 Runner.TYPE_HTML)); 130 t.setDaemon(true); 131 t.start(); 132 } 133 134 /** 135 * 以GET方法获取网页,编码方式为 gb2312,超时或编码错误返回null 136 * 137 * @param strUrl 138 * 网页URL地址 139 * @return 返回网页的字符串 140 */ 141 public String getHtml(String strUrl) { 142 return getHtml(strUrl, null, false, "gb2312"); 143 } 144 145 /** 146 * 以GET方法获取网页,超时或编码错误返回null 147 * 148 * @param strUrl 149 * 网页URL地址 150 * @param encoding 151 * 编码方式 152 * @return 返回网页的字符串 153 */ 154 public String getHtml(String strUrl, String encoding) { 155 return getHtml(strUrl, null, false, encoding); 156 } 157 158 /** 159 * 根据GET或POST方法获取网页,超时返回null 160 * 161 * @param strUrl 162 * 网页URL地址 163 * @param strPost 164 * POST 的数据 165 * @param isPost 166 * 是否 POST,true 则为POST ,false 则为 GET 167 * @param encoding 168 * 编码方式 169 * @return 返回网页的字符串 170 */ 171 public String getHtml(String strUrl, String strPost, boolean isPost, String encoding) { 172 String ret = null; 173 try { 174 byte[] data = getHtmlBytes(strUrl, strPost, isPost, encoding); 175 if (data != null) 176 ret = new String(data, encoding); 177 } catch (UnsupportedEncodingException e) { 178 // TODO Auto-generated catch block 179 } 180 return ret; 181 } 182 183 /** 184 * 根据GET或POST方法获取网络数据,超时返回null 185 * 186 * @param strUrl 187 * 网页URL地址 188 * @param strPost 189 * POST 的数据 190 * @param isPost 191 * 是否POST,true则为POST,false则为 GET 192 * @param encoding 193 * 编码方式 194 * @return 返回bytes 195 */ 196 public byte[] getHtmlBytes(String strUrl, String strPost, boolean isPost, String encoding) { 197 byte[] ret = null; 198 HttpURLConnection httpCon = null; 199 InputStream is = null; 200 try { 201 URL url = new URL(strUrl); 202 httpCon = (HttpURLConnection) url.openConnection(); 203 httpCon.setReadTimeout(timeout); 204 httpCon.setConnectTimeout(timeout); 205 httpCon.setUseCaches(false); 206 httpCon.setInstanceFollowRedirects(true); 207 httpCon.setRequestProperty("Referer", referer); 208 httpCon.setRequestProperty("Content-Type", CONTENT_TYPE); 209 httpCon.setRequestProperty("Accept", ACCEPT); 210 httpCon.setRequestProperty("User-Agent", USER_AGENT); 211 httpCon.setRequestProperty("Cookie", cookies.toString()); 212 213 if (isPost) { 214 httpCon.setDoOutput(true); 215 httpCon.setRequestMethod("POST"); 216 httpCon.connect(); 217 218 OutputStream os = null; 219 try { 220 os = httpCon.getOutputStream(); 221 os.write(URLEncoder.encode(strPost, encoding).getBytes()); 222 os.flush(); 223 } finally { 224 if (os != null) 225 os.close(); 226 } 227 } 228 229 // 获取数据 230 is = httpCon.getInputStream(); 231 ByteArrayBuffer baBuffer = null; 232 byte[] buffer = new byte[BUFFER_LENGTH]; 233 int rNum = 0; 234 // 若读取的数据长度小于 BUFFER_LENGTH,说明读取的 235 // 内容小于 BUFFER_LENGTH 已经一次性读取完毕 236 // 这个时候并不用创建 ByteArrayBuffer 237 // 238 // 以上并不适用 239 // if ((rNum = is.read(buffer)) < BUFFER_LENGTH) { 240 // ret = buffer; 241 // } else { 242 baBuffer = new ByteArrayBuffer(BUFFER_LENGTH << 1); 243 // baBuffer.append(buffer, 0, BUFFER_LENGTH); 244 while ((rNum = is.read(buffer)) != -1) { 245 baBuffer.append(buffer, 0, rNum); 246 } 247 ret = baBuffer.toByteArray(); 248 // } 249 250 } catch (Exception e) { 251 // TODO Auto-generated catch block 252 Log.e(TAG, e.getMessage() + ":" + e.getCause()); 253 } finally { 254 if (is != null) { 255 try { 256 is.close(); 257 } catch (IOException e) { 258 // TODO Auto-generated catch block 259 260 } 261 } 262 // 更新 Cookie 263 if (httpCon != null) { 264 cookies.putCookies(httpCon.getHeaderField("Set-Cookie")); 265 // 更新 referer 266 referer = strUrl; 267 httpCon.disconnect(); 268 } 269 } 270 return ret; 271 } 272 273 /** 274 * 新建一个线程获取一张网页图片 275 * 276 * @param strUrl 277 * @param handler 278 * 用于向发起本次调用的线程发送结果信息 279 * @param what 280 * handler中的what标记 281 */ 282 public void getBitmapByThread(String strUrl, Handler handler, int what) { 283 if (handler == null) 284 throw new NullPointerException("handler is null."); 285 286 Thread t = new Thread(new Runner(strUrl, null, false, null, handler, what, Runner.TYPE_IMG)); 287 t.setDaemon(true); 288 t.start(); 289 } 290 291 /** 292 * 获取一张网页图片 293 * 294 * @param strUrl 295 * 网页图片的URL地址 296 * @return 297 */ 298 public Bitmap getBitmap(String strUrl) { 299 byte[] data = getHtmlBytes(strUrl, null, false, null); 300 return BitmapFactory.decodeByteArray(data, 0, data.length); 301 } 302 303 private class Runner implements Runnable { 304 public final static int TYPE_HTML = 1; 305 public final static int TYPE_IMG = 2; 306 307 private String strUrl; 308 private String strPost; 309 private boolean isPost; 310 private String encoding; 311 private Handler handler; 312 private int what; 313 private int type; 314 315 public Runner(String strUrl, String strPost, boolean isPost, String encoding, 316 Handler handler, int what, int type) { 317 this.strUrl = strUrl; 318 this.strPost = strPost; 319 this.isPost = isPost; 320 this.encoding = encoding; 321 this.handler = handler; 322 this.what = what; 323 this.type = type; 324 } 325 326 @Override 327 public void run() { 328 // TODO Auto-generated method stub 329 Object obj = null; 330 switch (type) { 331 case TYPE_HTML: 332 obj = getHtml(strUrl, strPost, isPost, encoding); 333 break; 334 case TYPE_IMG: 335 obj = getBitmap(strUrl); 336 break; 337 } 338 synchronized (handler) { 339 handler.sendMessage(handler.obtainMessage(what, obj)); 340 } 341 } 342 343 } 344 }
Cookies.java
1 package com.whizen.servicedemo.util; 2 3 import java.util.HashMap; 4 import java.util.Map.Entry; 5 import java.util.Set; 6 7 /** 8 * 非同步保存Cookie的键值 9 * 10 * @author SomeWind 11 * 12 */ 13 public class Cookies { 14 15 private HashMap<String, String> hashMap; 16 17 public Cookies() { 18 hashMap = new HashMap<String, String>(); 19 } 20 21 /** 22 * 清除 Cookies 里面的所有 Cookie 记录 23 */ 24 public void clear() { 25 hashMap.clear(); 26 } 27 28 /** 29 * 根据 key 获取对应的 Cookie 值 30 * 31 * @param key 32 * 要获取的 Cookie 值的 key 33 * @return 如果不存在 key 则返回 null 34 */ 35 public String getCookie(String key) { 36 return hashMap.get(key); 37 } 38 39 /** 40 * 在 Cookies 里设置一个 Cookie 41 * 42 * @param key 43 * 要设置的 Cookie 的 key 44 * @param value 45 * 要设置的 Cookie 的 value 46 */ 47 public void putCookie(String key, String value) { 48 hashMap.put(key, value); 49 } 50 51 /** 52 * 在 Cookies 里面设置传入的 cookies 53 * 54 * @param cookies 55 */ 56 public void putCookies(String cookies) { 57 if (cookies == null) 58 return; 59 60 String[] strCookies = cookies.split(";"); 61 for (int i = 0; i < strCookies.length; i++) { 62 for (int j = 0; j < strCookies[i].length(); j++) { 63 if (strCookies[i].charAt(j) == '=') { 64 this.putCookie(strCookies[i].substring(0, j), 65 strCookies[i].substring(j + 1, strCookies[i].length())); 66 } 67 } 68 } 69 } 70 71 /** 72 * 获取 Cookies 的字符串 73 */ 74 @Override 75 public String toString() { 76 if (hashMap.isEmpty()) { 77 return ""; 78 } 79 80 Set<Entry<String, String>> set = hashMap.entrySet(); 81 StringBuilder sb = new StringBuilder(set.size() * 50); 82 for (Entry<String, String> entry : set) { 83 sb.append(String.format("%s=%s;", entry.getKey(), entry.getValue())); 84 } 85 sb.delete(sb.length() - 1, sb.length()); 86 return sb.toString(); 87 } 88 }
原文出处:http://www.cnblogs.com/newcj/archive/2011/05/11/2043147.html
浙公网安备 33010602011771号