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

Package Com.handspeaker.network;import Java.io.ioexception;import Java.io.unsupportedencodingexception;import Java.net.uri;import Java.net.urisyntaxexception;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Org.apache.http.httpresponse;import Org.apache.http.client.clientprotocolexception;import Org.apache.http.client.httpclient;import Org.apache.http.client.methods.httppost;import Org.apache.http.entity.stringentity;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.params.httpconnectionparams;import Org.apache.http.params.httpparams;import Org.apache.http.protocol.http;import org.apache.http.util.EntityUtils; Import Org.json.jsonobject;import Android.app.activity;import Android.content.context;import Android.net.connectivitymanager;import Android.os.handler;import android.util.log;/** * * for Encapsulation & Simplified HTTP communication * */    public class Postrequest implements Runnable {private static final int no_server_error=1000; Server toAddress public static final String URL = "Fill your own url";    Some request types public final static String ADD = "/add";    Public final static String UPDATE = "/update";    Public final static String PING = "/ping";    Some parameters private static int connectiontimeout = 60000;    private static int sockettimeout = 60000;    Class static variable private static HttpClient httpclient=new defaulthttpclient ();    private static Executorservice Executorservice=executors.newcachedthreadpool ();    private static Handler Handler = new Handler ();    Variable private String strresult;    Private HttpPost HttpPost;    Private HttpResponse HttpResponse;    Private Onreceivedatalistener Onreceivedatalistener;    private int statusCode;        /** * constructor, initialize some variables that can be reused */public postrequest () {strresult = null;        HttpResponse = null;    HttpPost = new HttpPost (); /** * Register to receive data listener * @param listener */public void Setonreceivedatalistener (Onreceivedatalistener li Stener) {        Onreceivedatalistener = listener;     }/** * Initializes httppost * * @param requesttype * Request type * @param namevaluepairs based on different request types * Parameters that need to be passed */public void Inirequest (String requesttype, Jsonobject jsonobject) {Httppost.addhea        Der ("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 (new URI (URL + RequestType)); Httppost.setentity (New Stringentity (Jsonobject.tostring (), HTTP.        Utf_8));        } catch (URISyntaxException E1) {e1.printstacktrace ();      } catch (Unsupportedencodingexception e) {      E.printstacktrace ();    }}/** * New thread to send HTTP request */public void execute () {Executorservice.execute (this); }/** * Detects network status * * @return true is available else false */public static Boolean checknetstate (Acti Vity activity) {Connectivitymanager Connmanager = (connectivitymanager) activity. Getsystemservice (        Context.connectivity_service);        if (connmanager.getactivenetworkinfo () = null) {return Connmanager.getactivenetworkinfo (). isavailable ();    } return false;        /** * Specific execution code to send HTTP request */@Override public void Run () {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 (); The finally {if (HttpResponse! = null) {StatusCode = Httpresponse.getstatusline (). Getstatuscode (            );            } else {statuscode=no_server_error;                } if (Onreceivedatalistener!=null) {//Onreceivedata method for registering listeners is added to the message queue to execute                        Handler.post (New Runnable () {@Override public void run () {                    Onreceivedatalistener.onreceivedata (Strresult, StatusCode);            }                });         }}}/** * Listener for receiving and processing HTTP request Results * */public interface Onreceivedatalistener {/** * The callback function for receiving the result data * from POST request, and further processing would be do         Here * @param strresult the result in string style. * @param StatusCode The status of the post */public abstract VoiD onreceivedata (String strresult,int StatusCode); }}

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

Ext.: http://www.cnblogs.com/hrlnw/p/4118480.html

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