[Original] a convenient tool for android to access http resources-HttpHelper

Source: Internet
Author: 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;/*** tool class to help you access http resources ** @ 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 ();}/*** get timeout time, the default value is 300000 milliseconds, that is, 5 minutes ** @ return */public int getTimeout () {return timeout ;} /*** set the timeout value to ReadTimeOut and ConnectTimeout. The unit of milliseconds is ** @ param timeout */public void setTimeout (int timeout) {this. timeout = timeout;}/*** get Referer ** @ return */Public String getReferer () {return referer;}/*** set Referer ** @ return */public void setReferer (String referer) {this. referer = referer;}/*** use the GET method to create a thread to obtain the webpage. The encoding method is gb2312, return null due to timeout or Encoding Error ** @ param strUrl * webpage URL * @ param handler * is used to send result information to the thread that initiates this call * @ param what * what mark in handler * /public void getHtmlByThread (String strUrl, handler handler, int what) {getHtmlByThread (strUrl, null, false ," Gb2312 ", handler, what);}/*** use the GET method to create a thread to obtain the webpage, return null ** @ param strUrl * webpage URL * @ param encoding * encoding method * @ param handler * for sending result information to the thread that initiates this call * @ param what mark in what * handler */public void getHtmlByThread (String strUrl, string encoding, Handler handler, int what) {getHtmlByThread (strUrl, null, false, encoding, handler, what );} /*** create a thread Based on the GET or POST method to obtain the webpage, and return null upon timeout ** @ param strUrl * webpage URL The data at the address * @ param strPost * POST * @ param isPost * is POST, and true indicates POST, false indicates the GET * @ param encoding * encoding method * @ param handler * used to send the result information to the thread initiating this call * @ param what * what mark in handler */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 Runn Er (strUrl, strPost, isPost, encoding, handler, what, Runner. TYPE_HTML); t. setDaemon (true); t. start ();}/*** GET the webpage using the GET method. The encoding method is gb2312, return null ** @ param strUrl * webpage URL * @ return webpage String */public String getHtml (String strUrl) {return getHtml (strUrl, null, false, "gb2312");}/*** GET the webpage using the GET method, return null ** @ param strUrl * webpage URL * @ param encoding * encoding method * @ return returns webpage String */public String get Html (String strUrl, String encoding) {return getHtml (strUrl, null, false, encoding);}/*** GET the webpage using the GET or POST method, return null ** @ param strUrl * webpage URL * @ param strPost * POST Data * @ param isPost * Whether to POST, true is POST, if false is set to GET * @ param encoding * encoding mode * @ return, the webpage String */public String getHtml (String strUrl, String strPost, boolean isPost, String encoding) is returned) {String ret = null; try {byte [] data = getHtm LBytes (strUrl, strPost, isPost, encoding); if (data! = Null) ret = new String (data, encoding);} catch (UnsupportedEncodingException e) {// TODO Auto-generated catch block} return ret ;} /*** obtain network data based on the GET or POST method, return null ** @ param strUrl * webpage URL * @ param strPost * POST Data * @ param isPost * Whether to POST, true is POST, if the value is false, the GET * @ param encoding * encoding method * @ return returns 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); htt PCon. 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 () ;}// obtain data is = httpCon. getInputStream (); ByteArrayBuffer baBuffer = null; byte [] buffer = new byte [BUFFER_LENGTH]; int rNum = 0; // If the read data length is less than BUFFER_LENGTH, it indicates that the read // content is less than BUFFER_LENGTH and has been read at a time. // at this time, the ByteArrayBuffer is not created. // The above does not apply. // 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} // update Cookieif (httpCon! = Null) {cookies. putCookies (httpCon. getHeaderField ("Set-Cookie"); // update refererreferer = strUrl; httpCon. disconnect () ;}} return ret ;} /*** create a thread to obtain a webpage image ** @ param strUrl * @ param handler * is used to send the result information to the thread that initiates this call * @ param what * handler's mark of 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 ();}/*** get a webpage image ** @ param strUrl * URL of the webpage image * @ 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;/*** key value for non-synchronous Cookie storage ** @ author SomeWind **/public class Cookies {private HashMap <String, String> hashMap; public Cookies () {hashMap = new HashMap <String, String> () ;}/ *** clear all Cookie records in Cookies */public void clear () {hashMap. clear ();} /*** obtain the corresponding Cookie value based on the key ** @ param key * key of the Cookie value to be obtained * @ return if the key does not exist */public String getCookie (String key) {return hashMap. get (key );} /*** set a Cookie in Cookies ** @ param key * the key of the Cookie to be set * @ param value * the value of the Cookie to be set */public void putCookie (String key, string value) {hashMap. put (key, value);}/*** set the incoming Cookies in 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 () ;}}}/ *** cookie String */@ 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 ();}}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.