Android HTTP Tool

Source: Internet
Author: User
Import Java. io. dataoutputstream; import Java. io. file; import Java. io. fileinputstream; import Java. io. ioexception; import Java. io. inputstream; import java.net. httpurlconnection; import java.net. URL; import Java. util. arraylist; import Java. util. list; import Org. apache. HTTP. httpentity; import Org. apache. HTTP. httpresponse; import Org. apache. HTTP. namevaluepair; import Org. apache. HTTP. client. clientprotocolexception; Import Org. apache. HTTP. client. httpclient; import Org. apache. HTTP. client. entity. urlencodedformentity; import Org. apache. HTTP. client. methods. httpget; import Org. apache. HTTP. client. methods. httppost; import Org. apache. HTTP. entity. fileentity; import Org. apache. HTTP. impl. client. defaulthttpclient; import Org. apache. HTTP. message. basicnamevaluepair; import Org. apache. HTTP. params. httpparams; import Org. apache. HTTP. Util. entityutils; import Org. JSON. jsonexception; import android. graphics. bitmap; import android. graphics. bitmapfactory; import android. util. log; import COM. leopard. health. model. constants; import COM. leopard. health. model. response. baseresponse; import COM. leopard. health. service. impl. userserviceimpl;/***** HTTP tool ** @ author wyyl1 ** @ date 2012-9-13 */public class httputil {Private Static final string cod Ing_utf_8 = "UTF-8"; public static baseresponse sendpost (string URL) throws clientprotocolexception, ioexception, jsonexception {// httppost connection object httppost httprequest = new httppost (URL ); // obtain the default httpclienthttpclient httpclient = new defaulthttpclient (); // obtain httpresponsehttpresponse httpresponse = httpclient.exe cute (httprequest); If (httpresponse. getentity ()! = NULL) {// obtain the returned string strresult = entityutils. tostring (httpresponse. getentity (); baseresponse respones = new baseresponse (strresult); respones. sethttpcode (httpresponse. getstatusline (). getstatuscode (); Return respones;} else {return NULL;} public static baseresponse sendpost (string URL, list <namevaluepair> Params) throws clientprotocolexception, ioexception, jsonexception {// httppost connection object httppost Httprequest = new httppost (URL); // Add the parameter to be passed // set the character set httpentity = new urlencodedformentity (Params, coding_utf_8); // request httprequesthttprequest. setentity (httpentity); // get the default response httpclient = new defaulthttpclient (); // get httpresponsehttpresponse httpresponse = httpclient.exe cute (httprequest); If (httpresponse. getentity ()! = NULL) {// obtain the returned string strresult = entityutils. tostring (httpresponse. getentity (); log. D ("statuscode", "" + httpresponse. getstatusline (). getstatuscode (); log. D ("returned string", strresult); baseresponse respones = new baseresponse (strresult); respones. sethttpcode (httpresponse. getstatusline (). getstatuscode (); Return respones;} else {return NULL;} public static baseresponse sendpost (string URL, httpparams Pa Rams, file, string contenttype) throws clientprotocolexception, ioexception, jsonexception {// httppost connection object httppost httprequest = new httppost (URL ); // Add the parameter to be passed /// set the character set list <namevaluepair> paramshttpentity = new arraylist <namevaluepair> (); paramshttpentity. add (New basicnamevaluepair (constants. syn_sid, userserviceimpl. logineduser. getsessionid (); paramshttpentity. add (New basicnamevaluepair ("app_ I D ", constants. app_id); // httpentity = new urlencodedformentity (paramshttpentity, // coding_utf_8); // request httprequest // httprequest. setentity (httpentity); fileentity Fe = new fileentity (file, contenttype); httprequest. setentity (FE); // get the default response httpclient = new defaulthttpclient (); // get httpresponse "httpresponse = httpclient.exe cute (httprequest); If (httpresponse. Getentity ()! = NULL) {// obtain the returned string strresult = entityutils. tostring (httpresponse. getentity (); log. D ("statuscode", "" + httpresponse. getstatusline (). getstatuscode (); log. D ("returned string", strresult); baseresponse respones = new baseresponse (strresult); respones. sethttpcode (httpresponse. getstatusline (). getstatuscode (); Return respones;} else {return NULL;}/*** Upload File ** @ Param actionurl upload address * @ Param name the field name of the file received by the server * @ Param uploadfile address * @ Param newname the name you want to save on the server * @ return */public static string uploadfile (string actionurl, string name, string uploadfile, string newname) {string end = "\ r \ n"; string twohyphens = "--"; string boundary = "*****"; dataoutputstream DS = NULL; stringbuffer B = new stringbuffer (); try {URL url = new URL (actionurl); httpurlconnection con = (httpurlconnection) URL. openconnection ();/* Allow input and output without using cache */con. setdoinput (true); con. setdooutput (true); con. setusecaches (false);/* set the transfer method = post */con. setrequestmethod ("Post");/* setrequestproperty */con. setrequestproperty ("connection", "keep-alive"); con. setrequestproperty ("charset", "UTF-8"); con. setrequestproperty ("Content-Type", "multipart/form-data; boundary =" + boundary);/* Set dataoutputstream */DS = new dataoutputstream (con. g Etoutputstream (); DS. writebytes (twohyphens + boundary + end); DS. writebytes ("content-Disposition: Form-data;" + "name = \" IMG \ "; filename = \" "+ newname +" \ "" + end); DS. writebytes (end);/* Get the fileinputstream */fileinputstream fstream = new fileinputstream (uploadfile);/* Set 1024 bytes */INT buffersize = 1024 each write; byte [] buffer = new byte [buffersize]; int length =-1;/* read data from the file to the buffer */while (length = fstre Am. Read (buffer ))! =-1) {/* write data to dataoutputstream */Ds. write (buffer, 0, length);} Ds. writebytes (end); DS. writebytes (twohyphens + boundary + twohyphens + end);/* close streams */fstream. close (); DS. flush ();/* Get Response content */inputstream is = con. getinputstream (); int ch; while (CH = is. read ())! =-1) {B. append (char) CH);} log. D ("res", B. tostring ();} catch (exception e) {e. printstacktrace ();} finally {try {// close dataoutputstreamds. close ();} catch (ioexception e) {e. printstacktrace () ;}} return B. tostring ();}/*** download image * @ Param URL * @ return */public static bitmap downloadimage (string URL) {httpclient = new defaulthttpclient (); try {httpget request = new httpget (URL); log. D ("downloadimgurl", "[] [] [] [] [] [] [] =" + URL); httpresponse response = httpclient.exe cute (request ); byte [] image = entityutils. tobytearray (response. getentity (); bitmap mbitmap = bitmapfactory. decodebytearray (image, 0, image. length); Return mbitmap;} catch (ioexception e) {// covers: // clientprotocolexception // connecttimeoutexception // connectionpooltimeoutexception // sockettimeoutexceptione. printstacktrace ();} return NULL ;}}

References:

File Upload method: Google Android SDK development example

Image download method: proficient in android3

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.