Android Learning 24 (Best practices for network programming)

Source: Internet
Author: User



The previous blog has explained the usage of httpurlconnection and httpclient, learned how to initiate HTTP requests, and resolved the server to return
The data. But you may have found out that because an application can use network functionality in many places, and the code that sends HTTP requests is basically the same, it's obviously not good to write the code that sends the HTTP request every time.
Typically, we should extract these generic network operations into a common class and provide a static method that simply calls this method when you want to initiate a network request. For example, the following wording:

Package Com.jack.networktest;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;public class HttpUtil {public static String Sendhttprequest (String address) {httpurlconnection Connection=null;try{url url=new URL (address); connection = ( httpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); Connection.setdoinput (true); Connection.setdooutput (true); InputStream in= Connection.getinputstream (); BufferedReader reader=new BufferedReader (New InputStreamReader (in)); StringBuilder response=new StringBuilder (); String Line;while ((Line=reader.readline ())!=null) {response.append (line);} return response.tostring ();} catch (Exception e) {e.printstacktrace (); return E.getmessage ();} Finally{if (connection!=null) {connection.disconnect ();}}}}


This can be written whenever an HTTP request is to be launched:
String address= "http://www.baidu.com";
String response=httputil.sendhttprequest (address);


After getting the data to the server response, we can parse and process it. However, it is important to note that network requests are usually time-consuming, and that the Sendhttprequest method does not have threads open inside, which can cause the main thread to block when the Sendhttprequest method is called. You might say that opening a thread inside the Sendhttprequest method doesn't solve the problem of blocking. It's not that simple, because if we open a thread in the Sendhttprequest method to initiate an HTTP request, then the data for the server response cannot be returned, and all the time-consuming logic is thread on the Strand. The Sendhttprequest method ends when the server is still in a response, and of course it cannot return the data for the response.
So how do you solve this situation? In fact, the solution can use the Java callback mechanism, let's learn how the callback mechanism is used.
You first need to define an interface, such as naming it Httpcallbacklistener, as shown in the following code:
Public INTERFAC httpcallbacklistener{
void OnFinish (String response);
void OnError (Exception e);
}
As you can see, we have defined two methods in the interface, and the OnFinish (String response) method indicates that when the server successfully responds to our request
, OnError (Exception e) is called when there is an error in the network operation. Both of these methods have parameters,
The parameters in the OnFinish (String response) method represent the data returned by the server, and the onerror (Exception e) method
The details of the error are recorded in the parameters.

then modify the code in the Httputil:

Import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import Java.net.httpurlconnection;import Java.net.url;public class Httputil {public static void Sendhttprequest (final String Address,final Httpcallbacklistener Listener) {New Thread (new Runnable () {@Overridepublic void Run () {//TODO Auto-generated method Stubhttpurlconnection Connection=null;try{url url=new URL (address); connection = ( httpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); Connection.setdoinput (true); Connection.setdooutput (true); InputStream in= Connection.getinputstream (); BufferedReader reader=new BufferedReader (New InputStreamReader (in)); StringBuilder response=new StringBuilder (); String Line;while ((Line=reader.readline ())!=null) {response.append (line);} if (listener!=null) {//Callback OnFinish () method Listener.onfinish (Response.tostring ());}} catch (Exception e) {if (listener!=null) {//Callback OnError () method Listener.onerror (e);}}finally{if (connection!=null) {connection.disconnect ();}}}). Start ();}}


We first added a httpcallbacklistener parameter to the Sendhttprequest method and opened a child thread inside the method, and then
Perform a specific network operation in a child thread. Note that it is not possible to return data through a return statement in a child thread, so here we pass the server response data into the Httpcallbacklistener onfinish () method, and if an exception occurs, pass the exception reason into the OnError () method.
Now the Sendhttprequest method receives two parameters, so we also need to pass in the Httpcallbacklistener instance when we call it.
As shown below:

Httputil.sendhttprequest (address,new Httpcallbacklistener () {public   void OnFinish (String response) {   // Here the concrete logic is executed according to the return content   } public      void OnError (Exception e) {      //Where the exception is handled   }     });


In this case, when the server responds successfully, we can process the response data in the OnFinish method, similarly, if an exception occurs, the exception can be handled in the OnError method. As a result, we have cleverly used the callback mechanism to successfully return the response data to the caller.
It is also important to note that the OnFinish method and the OnError method are ultimately run in a sub-thread, so we are not allowed to perform any of the
UI actions, if you need to update the UI based on the returned results, you still want to use the asynchronous message processing mechanism.




http://blog.csdn.net/j903829182/article/details/42521437



Android Learning 24 (Best practices for network programming)

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.