Android Development Network Request Communication Special topic (II): httpclient-based file upload download

Source: Internet
Author: User

Previous topic Android Development Network Request Communication Topic (i): Request communication based on HttpURLConnection we explained how to use HttpURLConnection to achieve basic text data transfer. Generally in the actual development we can be used to transfer XML or JSON-formatted data. Today we will explain another way of HTTP network request: HttpClient, and implement file upload and download.

Here is a digression, in fact, these network requests have a lot of third-party jar packages can be used, these packages are well encapsulated. If you just want to use it, we'll just take someone else's jar package. Bloggers here recommend a call Xutils tool class, this thing is actually good, I believe many people know that this tool is a blogger's colleague wrote a classmate. The following bloggers will also write a picture of the project, will also explain the xutils inside the picture class implementation principle. Okay, get to the point today.

As with the previous topic, we'll start with the basic usage of the two request methods before we go into encapsulation.


First, based on the implementation of httpclient file upload let's take a look at the most basic upload code
1. Uploading files on the Android side

/** * @Title: Updatefile * @Description: File upload * @throws */private void Updatefile () {//Create a new HttpClient class HttpClient Httpclien t = new defaulthttpclient ();//Post file upload httppost post = new HttpPost ("http://192.168.1.107:10010/MINATest/servlet/ Uploadservlet ");//Get the uploaded picture string filePath = Environment.getexternalstoragedirectory (). GetAbsolutePath () +"/ Justice.jpg ";//processing uploaded file Filebody filebody = new Filebody (new file (FilePath)); Stringbody stringbody = null;try {stringbody = new Stringbody ("Description of the file");} catch (Unsupportedencodingexception e) {//TODO A Uto-generated catch Blocke.printstacktrace ();} multipartentity entity = new Multipartentity (), Entity.addpart ("file", Filebody), Entity.addpart ("desc", stringbody); Post.setentity (entity); HttpResponse response = null;try {response = Httpclient.execute (post);} catch (Clientprotocolexception e) { E.printstacktrace ();} catch (IOException e) {e.printstacktrace ();} if (Httpstatus.sc_ok = = Response.getstatusline (). Getstatuscode ()) {//Get the returned entity, in general, the stream returned with the POST request is the actualBody to get, in here do not need so Bo Master will not write. Httpentity Entitys = response.getentity (), if (entity! = null) {System.out.println (Entity.getcontentlength ()); try { System.out.println (entityutils.tostring (Entitys));} catch (ParseException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ()}}} Httpclient.getconnectionmanager (). shutdown ();}

2, service-side dopost processing
/** * * @param request * The request send by the client to the server * @param response * The RESPO              NSE send by the server to the client * @throws servletexception * If an error occurred * @throws IOException * If an error occurred */@Overridepublic void DoPost (HttpServletRequest request, httpservletresponse response) t Hrows Servletexception, IOException {boolean ismulti = servletfileupload.ismultipartcontent (Request), if (IsMulti) { String Realpath = Request.getsession (). Getservletcontext (). Getrealpath ("/vioce"); System.out.println (Realpath); File dir = new file (Realpath), if (!dir.exists ()) {dir.mkdirs ();} Fileitemfactory factory = new Diskfileitemfactory (); Servletfileupload upload = new Servletfileupload (factory); Upload.setheaderencoding ("UTF-8"); String fileName = null;try {list<fileitem> items = upload.parserequest (request); for (Fileitem Item:items) {if (ite M.isformfield ()) {String name = Item.getfieldname (); String value = Item.getstriNg ("UTF-8"); SYSTEM.OUT.PRINTLN (name + "-" + value);} else {item.write (dir, Item.getname ())); fileName = Item.getname ();}} Response.setcontenttype ("Text/*;charset=utf-8"); Response.getwriter (). Write ("Upload succeeded");} catch (Exception e) {e.printstacktrace ();}}}
We can see that when the upload method is executed, the image uploaded from the android side is already in the folder specified on the server, and the successful upload of the server is also printed in the Logcat of the Android side.
3, the download of the Android side fileHere Bo Master easy, directly to write the address to die.
/** * @Title: DownLoadFile * @Description: File download * @throws */private void DownLoadFile () {HttpClient httpClient1 = new Defau Lthttpclient (); HttpGet HttpGet1 = new HttpGet ("http://192.168.31.144:10010/MINATest/vioce/strikefreedom.jpg"); try {HttpResponse HttpResponse1 = Httpclient1.execute (HTTPGET1); Statusline statusline = Httpresponse1.getstatusline (); if (statusline.getstatuscode () = =) {String FilePath = Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/freedom.jpg"; File path filename = new file (FilePath); FileOutputStream outputstream = new FileOutputStream (file); InputStream InputStream = Httpresponse1.getentity (). GetContent (); byte b[] = new Byte[1024];int J = 0;while ((j = Inputstream.read (b))! =-1) {outputstream.write (b, 0, j);} Outputstream.flush (); Outputstream.close ();}} catch (Exception e) {e.printstacktrace ();} finally {Httpclient1.getconnectionmanager (). shutdown ();}}



Ii. encapsulation of HttpClient Class 1, Package logicAlthough HttpClient has a certain encapsulation with respect to HttpURLConnection, the API is relatively concise, but we can still do this on the basis of another package. The package structure is similar to that of the previous article. In the previous topic, we used four classes to encapsulate. Here we use the Android Asynctask class to replace the handler, also can save a callback to listen. Here the callback interface design in fact, according to the needs of their own to set up, bloggers take the previous callback interface to use. We need three classes this time.
1, HTTP Access Manager 2, Task Asynctask Class 3, HTTP access result event processing callback interface.the entire logical relationship is: The HTTP access manager takes a GET or POST request request, when the result of the listener tells the message Communication Manager what message should be sent to the UI thread, the UI thread more message Communication Manager sent over the message, Invokes the corresponding event-handling callback interface.
·
Next, let's write one by one for these three classes.
2. HTTP Access Manager
Package Com.example.nettest;import Java.io.ioexception;import Java.io.inputstream;import Java.io.unsupportedencodingexception;import Java.util.arraylist;import Java.util.list;import Org.apache.commons.lang.stringutils;import Org.apache.http.httphost;import Org.apache.http.httprequest;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.CookieStore; 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.conn.params.connroutepnames;import Org.apache.http.entity.bytearrayentity;import Org.apache.http.entity.stringentity;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.message.basicnamevaluepair;import Org.apache.http.params.basichttpparams;import Org.apache.http.params.httpconnectionparams;import Org.apache.http.params.httpparams;import com.lidroid.xutils.http.client.multipart.multipartentity;/*** @ClassName: Freedomhttpclientutil * @author victor_freedom ([email protected]) * @createddate 2015-1-25 PM 11:0 4:59 * @Description: */public class Freedomhttpclientutil {private defaulthttpclient client;/** request Interface */private Httpreques T httprequest;/** response Interface */private HttpResponse response;/** method */private string mmethod;public static final String POST = "  Post ";p ublic static final string get =" Get ";p rivate static final String TAG =" Freedomhttpclientutil ";p ublic static final int HTTP_OK = 200;private Void Open () {httpparams params = new Basichttpparams (); Httpconnectionparams.setconnectiontimeout (params, 5000); Set Connection Timeout httpconnectionparams.setsotimeout (params, 5000); Set Request Timeout client = new Defaulthttpclient (params); try {//If not WiFi, we need to set the APN parameter of the phone if (Stringutils.isnotblank ( Configparams.proxy) {Httphost PROXY = new Httphost (configparams.proxy,configparams.port); Client.getparams (). Setparameter (connroutepnames.default_proxy,proxy);} The default is to use the UTF-8 encoding Httprequest.setheader ("Charset", "UTF-8");} catch (Exception e) {throw new freedomexception (Freedomexception.network_anomaly);}} /** * can handle both post and get two forms of request * * @param URL * @param method */public void Open (string url, string method) {if (stringutils. Isnotblank (method) && Stringutils.isnotblank (URL)) {if (Method.equals (POST)) {HttpRequest = new HttpPost (URL); Mmethod = POST;} else {HttpRequest = new HttpGet (URL); mmethod = GET;} Open ();}} /** * @Title: Sethttppostheader * @Description: Set request Header * @param name * @param value * @throws */public void Sethttpposthead ER (string name, String value) {if (HttpRequest = = null) {throw new freedomexception (freedomexception.network_anomaly);} if (Stringutils.isnotblank (name)) {Httprequest.setheader (name, value);}} /** * @Title: SetContent * @Description: Set BYTE type entity * @param info * @throws */public void setcontent (byte[] info) {if (httpre Quest = = null) {throw new freedomexception (freedomexception.network_anomaly);} if (Info.length > 0) {bytearrayentity entity = new Bytearrayentity (info);HttpRequest instanceof HttpPost) ((HttpPost) HttpRequest). Setentity (entity);}} /** * @Title: Setstringentity * @Description: Set string entity * @param datas * @throws */public void setstringentity (String datas {if (HttpRequest = = null) {throw new freedomexception (freedomexception.network_anomaly);} if (null! = Datas) {try {stringentity entity = new stringentity (datas); if (HttpRequest instanceof HttpPost) ((HttpPost) htt prequest). setentity (entity);} catch (Unsupportedencodingexception e) {e.printstacktrace ();}}} /** * @Title: Setjsonstringentity * @Description: Set JSON data format entity * @param datas * @throws */public void setjsonstringentity ( String datas) {if (HttpRequest = = null) {throw new freedomexception (freedomexception.network_anomaly);} if (null! = Datas) {try {stringentity entity = new Stringentity (datas, "Utf-8"); Entity.setcontenttype ("Application/json" );//Entity.setcontentencoding ("Utf-8"); if (HttpRequest instanceof HttpPost) ((HttpPost) HttpRequest). Setentity ( entity);} catch (UnsupportedencodingexcEption e) {e.printstacktrace ();}}} /** * @Title: Setentitys * @Description: Set multi-parameter entity * @param datas * @throws */public void Setentitys (String ... datas) {if (H Ttprequest = = null) {throw new freedomexception (freedomexception.network_anomaly);} if (Datas.length > 0) {list<namevaluepair> Parameters = new arraylist<namevaluepair> (); for (int i = 0; I &l T Datas.length; i + = 2) {Parameters.Add (new Basicnamevaluepair (Datas[i], datas[i + 1]));} if (HttpRequest instanceof HttpPost) try {((httppost) HttpRequest). Setentity (New urlencodedformentity (Parameters, " UTF-8 "));} catch (Unsupportedencodingexception e) {e.printstacktrace ();}}} /** * @Title: Setdataentitys * @Description: Set data entity * @param mpentity * @throws */public void Setdataentitys (Multipartenti Ty mpentity) {if (HttpRequest = = null) {throw new freedomexception (freedomexception.network_anomaly);} if (HttpRequest instanceof HttpPost) {((HttpPost) HttpRequest). Setentity (mpentity);}} /** * @Title: Post * @Description: Send request * @throws EXCEption * @throws */public void post () throws Exception {if (HttpRequest = null) {throw new Freedomexception (freedomexcept Ion. Network_anomaly);} if (Mmethod.equals (POST)) {response = Client.execute ((httppost) httprequest);} else {response = Client.execute ((httpget ) (HttpRequest);}}  /** * @Title: Getcontentlength * @Description: Get back Content length * @return * @throws */public long getcontentlength () {Long result = 0;if (response = = null) {throw new freedomexception (freedomexception.network_anomaly);} result = Response.getentity (). Getcontentlength (); return result;} /** * @Title: Openinputstream * @Description: Get back Stream * @return * @throws illegalstateexception * @throws IOException * @thr oWS */public InputStream Openinputstream () throws Illegalstateexception,ioexception {if (response = = null) {throw new free Domexception (freedomexception.network_anomaly);} InputStream result = Response.getentity (). getcontent (); return result;} /** * @Title: Getcookiestore * @Description: Get cookie * @return * @throws */public COokiestore Getcookiestore () {if (null = = client) {throw new freedomexception (freedomexception.network_anomaly);} return Client.getcookiestore ();} /** * @Title: Getresponsecode * @Description: Get Return code * @return * @throws */public int getresponsecode () {int result;if (resp Onse = = null) {throw new freedomexception (freedomexception.network_anomaly);} result = Response.getstatusline (). Getstatuscode (); return result;} /** * @Title: Setrequestproperty * @Description: Set request Header * @param name * @param value * @throws */public void Setrequestprop Erty (string name, String value) {Sethttppostheader (name, value);} /** * @ClassName: Configparams * @author victor_freedom ([email protected]) * @createddate 2015-1-25 pm 11:11:05 * @De Scription: If it is not WiFi access, you need to set the parameter */public static class Configparams {public static string SRC = "";p ublic static string PROXY = "";p ublic static int port;public static string TYPE = "";p ublic static string MNC = "";}
2.TaskAsynctask classThis kind of writing, need to according to the actual business needs to set three parameters, I believe that the Asynctask class students know how to use this class. Do not know the students can also Baidu, there are many related articles on the Internet. Here we use the download file example to illustrate
Package Com.example.nettest;import Java.io.file;import Java.io.fileoutputstream;import java.io.InputStream;import Android.annotation.suppresslint;import Android.app.progressdialog;import Android.content.context;import Android.os.asynctask;import android.os.environment;/** * @ClassName: Freedomasyntask * @author victor_freedom ([email& Nbsp;protected]) * @createddate October 12, 2014 PM 10:07:36 * @Description: TODO * */public class Freedomasyntask extends Asyn Ctask<void, Integer, string> {private Freedomhttpcallbacklistener listener;public freedomasyntask ( Freedomhttpcallbacklistener listener,context Context, ProgressDialog mdialog, String path) {This.listener = listener;} @SuppressLint ("Defaultlocale") @Overrideprotected String doinbackground (Void ... params) {InputStream is = null; Freedomhttpclientutil http = new Freedomhttpclientutil (); Http.open ("http://192.168.31.144:10010/MINATest/vioce/ Strikefreedom.jpg ", freedomhttpclientutil.get); try {http.post (); if (http.getresponsecode () = = 200) {String FilePath = Environment.getexternalstoragedirectory (). GetAbsolutePath () + "/freedom.jpg"; File path filename = new file (FilePath); FileOutputStream outputstream = new FileOutputStream (file); InputStream InputStream = Http.openinputstream (); byte b[] = New Byte[1024];int J = 0;while ((j = Inputstream.read (b))! =-1) {outputstream.write (b, 0, j);} Outputstream.flush (); Outputstream.close (); return "Download succeeded";} else {return null;}} catch (Exception e) {e.printstacktrace (); return null;}} @Overrideprotected void Onprogressupdate (Integer ... values) {super.onprogressupdate (values);} @Overrideprotected void OnPreExecute () {Super.onpreexecute ();} @Overrideprotected void OnPostExecute (String result) {if (null! = result) {listener.action ( Freedomhttpcallbacklistener.event_get_data_success,result);} else {listener.action (freedomhttpcallbacklistener.event_get_data_eeeor,null);} Super.onpostexecute (result);}}
We can see that in the different return results, the action has a different parameter in the corresponding pass. Here the monitoring package Bo master lazy, directly so write, want to better perfect a bit actually should be able to do better. Interested students can go to perfect, bo master lazy. As an article on the listening class has already been said, here is not a detailed description of the use of our activity
3. Use in Activityvery simple to use, we only need a line of code to achieve the download of the file
if (Netutils.checknetwork (Mcontext)) {New Freedomasyntask (new Freedomhttpcallbacklistener () {@Overridepublic void Action (int code, Object obj) {//executes method according to return code}}). Execute ();

OK, the second article on HTTP access has been explained, hoping to help people who see this article.






Android Development Network Request Communication Special topic (II): httpclient-based file upload download

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.