Android uses HTTP protocol to communicate with server

Source: Internet
Author: User

There are many articles on the Internet about HTTP communication on Android, but most of them give only fragments of implementation code, some considerations and how to design a reasonable class to handle all HTTP requests and return results, which are generally not mentioned. So, I made a summary of this and gave me a solution.

First, we need to clarify the HTTP communication process, Android currently provides two kinds of HTTP communication methods,HttpURLConnection和HttpClient,HttpURLConnection多用于发送或接收流式数据,因此比较适合上传/下载文件,HttpClient相对来讲更大更全能,但是速度相对也要慢一点。在此只介绍HttpClient的通信流程:

1. Create a HttpClient object that can be used to send different HTTP requests multiple times

2. Create HttpPost or HttpGet objects, set parameters, and each time an HTTP request is sent, an object is required

3. Using the Execute method of httpclient to send the request and wait for the result, the method will block the current thread until the result is returned or an exception is thrown.

4. Handle the results and exceptions accordingly

According to the above process, there are a few things to consider when designing a class:

1.HttpClient objects can be reused, so they can be used as static variables for classes

2.httppost/httpget objects are generally not reusable (you can reuse them every time you request a parameter), so you can create a method to initialize and set up some resources to upload to the server

3. Currently Android no longer supports initiating HTTP requests in the UI thread, and should not actually do so, because it blocks the UI thread. Therefore, a child thread is also required to initiate an HTTP request that executes the Execute method

4. Different requests correspond to different return results, and a certain degree of freedom is required for handling the returned results (generally parsing the json& update UI).

5. The simplest approach is to send a message to the UI thread as appropriate whenever an HTTP request is sent, a child thread is used to send a request, a result is received in a child thread, or an exception is thrown. Finally, the result parsing and UI update are done in the handler Handlemessage method of the UI thread. While this is simple, the UI thread and HTTP requests are highly coupled and the code is messy and ugly.

For some of these reasons, I designed a postrequest class to meet my HTTP communication needs. I only use the POST request, if you need a GET request, you can also change to write Getrequest;;;;;ImportJava.util.concurrent.ExecutorService;Importjava.util.concurrent.Executors;ImportOrg.apache.http.HttpResponse;Importorg.apache.http.client.ClientProtocolException;Importorg.apache.http.client.HttpClient;ImportOrg.apache.http.client.methods.HttpPost;Importorg.apache.http.entity.StringEntity;Importorg.apache.http.impl.client.DefaultHttpClient;ImportOrg.apache.http.params.HttpConnectionParams;ImportOrg.apache.http.params.HttpParams;ImportOrg.apache.http.protocol.HTTP;Importorg.apache.http.util.EntityUtils;ImportOrg.json.JSONObject;;ImportAndroid.content.Context;;ImportAndroid.os.Handler;ImportAndroid.util.Log;/*** * for Encapsulation & Simplified HTTP communication **/ Public classPostrequestImplementsRunnable {Private Static Final intno_server_error=1000; //Server Address     Public Static FinalString url = "Fill your own url"; //Some request types     Public Final StaticString ADD = "/add";  Public Final StaticString UPDATE = "/update";  Public Final StaticString PING = "/ping"; //some parameters    Private Static intConnectionTimeout = 60000; Private Static intSockettimeout = 60000; //class static Variables    Private StaticHttpClient httpclient=Newdefaulthttpclient (); Private StaticExecutorservice executorservice=Executors.newcachedthreadpool (); Private StaticHandler Handler =NewHandler (); //variables    PrivateString strresult; PrivateHttpPost HttpPost; PrivateHttpResponse HttpResponse; PrivateOnreceivedatalistener Onreceivedatalistener; Private intStatusCode; /*** constructor, initialize some variables that can be reused*/     Publicpostrequest () {strresult=NULL; HttpResponse=NULL; HttpPost=NewHttpPost (); }        /*** Register to receive data listener *@paramListener*/     Public voidSetonreceivedatalistener (Onreceivedatalistener listener) {Onreceivedatalistener=Listener; }    /*** Initialize HttpPost according to different request type * *@paramRequestType * Request type *@paramNamevaluepairs * Parameters that need to be passed*/     Public voidinirequest (String RequestType, Jsonobject jsonobject) {Httppost.addheader ("Content-type", "Text/json"); Httppost.addheader ("CharSet", "UTF-8"); Httppost.addheader ("Cache-control", "No-cache"); Httpparams httpparameters=Httppost.getparams ();        Httpconnectionparams.setconnectiontimeout (Httpparameters, ConnectionTimeout);        Httpconnectionparams.setsotimeout (Httpparameters, sockettimeout);        Httppost.setparams (httpparameters); Try{Httppost.seturi (NewURI (URL +RequestType)); Httppost.setentity (Newstringentity (jsonobject.tostring (), HTTP.        Utf_8)); } Catch(URISyntaxException E1) {e1.printstacktrace (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); }    }    /*** Open a new thread to send an HTTP request*/     Public voidExecute () {Executorservice.execute ( This); }    /*** Detect Network status * *@returntrue is available else false*/     Public Static Booleanchecknetstate (activity activity) {Connectivitymanager Connmanager=(Connectivitymanager) activity. Getsystemservice (Context.connectivity_service); if(Connmanager.getactivenetworkinfo ()! =NULL) {            returnconnmanager.getactivenetworkinfo (). isavailable (); }        return false; }    /*** Specific execution code for sending HTTP requests*/@Override Public voidrun () {HttpResponse=NULL; Try{HttpResponse=Httpclient.execute (HttpPost); Strresult=entityutils.tostring (Httpresponse.getentity ()); } Catch(clientprotocolexception E1) {strresult=NULL;        E1.printstacktrace (); } Catch(IOException E1) {strresult=NULL;        E1.printstacktrace (); } finally {            if(HttpResponse! =NULL) {StatusCode=httpresponse.getstatusline (). Getstatuscode (); }            Else{StatusCode=No_server_error; }            if(onreceivedatalistener!=NULL)            {                //The Onreceivedata method of the registered listener is added to the message queue to (NewRunnable () {@Override Public voidrun () {onreceivedatalistener.onreceivedata (strresult, StatusCode);            }                }); }        }    }    /*** Listener for receiving and processing HTTP request results **/     Public InterfaceOnreceivedatalistener {/*** The callback function for receiving the result data * from POST request, and further processing wil L be do here *@paramstrresult The result in string style. * @paramStatusCode The status of the post*/         Public Abstract voidOnreceivedata (String strresult,intStatusCode); }}

The code uses the Observer pattern, and any class that needs to receive the result of the HTTP request implements an abstract method of the Onreceivedatalistener interface, while the Postrequest instance calls the Setonreceivedatalistener method, Register the Listener. The complete invocation steps are as follows:

1. Create the Postrequest object, implement the Onreceivedata interface, write your own Onreceivedata method

2. Registering listeners

3. Call Postrequest's Inirequest method to initialize the request

4. Invoke the Execute method of Postrequest

Possible improvements:

1. If you need more than one observer, you can register only a single listener to register multiple listeners and maintain a list of listeners.

2. Inirequest and execute can be merged if the requirements are simple and you want the invocation process to be more concise

If there is a better way or problem, please feel free to communicate

Android uses HTTP protocol to communicate with server

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: 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.