Complimentary HttpClient and httpurlconnection Light Network-"thread pool introduction and network Request Flow"

Source: Internet
Author: User

Reprint Annotated Source:http://blog.csdn.net/codingandroid/article/details/41748743


As a framework, it is necessary to deal with some of the more complex situations, under normal circumstances will not block, when the situation is more complex, there will be more than the situation of network requests, it is the case that we regulate to manage the best of course, so we need a thread pool.

First explain what is called the thread pool:

Whenever a thread is started, our usual code is new Thead () {}.start ();    New one object in the new one runnable this is relatively time-consuming, the resources we can save the province, the thread pool is quite with said: I maintain a pool, for example, put 5 off-the-shelf threads, requests come and do not have to go back to new directly can use, more than 5 times need to wait For Android's development, it's like Soundpool.

Just understand this, the code is not a few lines, put it up OH

Package Com.clxu.netframe.abstractinterface;import Java.util.concurrent.abstractexecutorservice;import Java.util.concurrent.arrayblockingqueue;import Java.util.concurrent.threadpoolexecutor;import java.util.concurrent.timeunit;/*** * @function thread pool * @author clxu * * 2014-11-25 */public class Defaultthreadpool {/* * * The blocking queue that is used to hold tasks waiting to be executed. (ordered FIFO blocking queue) */private static arrayblockingqueue<runnable> Mblockingqueue = new Arrayblockingqueue<runna    Ble> (, True);                                                        /** * thread pool */private static Abstractexecutorservice Mthreadpoolexecutor                                                                 = New Threadpoolexecutor (5, 7, Timeunit.seconds, Mblockingqueue,    New Threadpoolexecutor.discardoldestpolicy ());    private static Defaultthreadpool instance = NULL; public static Defaultthreadpool getinstance () {if (instance = = null) {instance = new Defaultthreadpool        ();    }    return instance;    }/** * Perform task * @param r */public void execute (Runnable r) {Mthreadpoolexecutor.execute (R);            }/** * Closes and waits for task execution to complete, does not accept new task */public static void shutdown () {if (mthreadpoolexecutor! = null) {        Mthreadpoolexecutor.shutdown (); }}/** * Closes, shuts down immediately, suspends all executing threads, does not accept new tasks */public static void Shutdownrightnow () {if (Mthreadpoolex            Ecutor = null) {Mthreadpoolexecutor.shutdownnow ();            try {//Set timeout is very short, forcing all tasks to close mthreadpoolexecutor.awaittermination (1, timeunit.microseconds);            } catch (Interruptedexception e) {e.printstacktrace (); }        }    }}




When used in the previous article there is a code mdefaultthreadpool.execute (asyncbaserequest); That's the thread pool, but what's the next one?


Masyncrequests.add (asyncbaserequest); This line of code is the function of maintaining the current activity of all requests, the current page closed, convenient to end all requests


There's a basic request class asyncbaserequest This class, this is the base class for the request, where we set the various processes for the network request, and the handling of the exception

Package Com.clxu.netframe.abstractinterface;import Java.io.ioexception;import Java.io.serializable;import Java.net.httpurlconnection;import Java.net.sockettimeoutexception;import Java.util.map;import Java.util.concurrent.timeoutexception;import Org.apache.http.conn.connecttimeoutexception;import Org.apache.http.conn.httphostconnectexception;import Com.clxu.netframe.r;import Com.clxu.netframe.constant.constant;import Com.clxu.netframe.exception.myexception;import Com.clxu.netframe.net.callback.parsecallback;import Com.clxu.netframe.net.callback.resultcallback;import com.clxu.netframe.util.logutil;/** * Function Description: Network request line base class * @author Clxu * Date Created: 2014-12-4 */public abstract class Asyncbasereque    St implements Runnable, Serializable {private static final long serialversionuid = 1L;    /** Log Print label */private static final String tag = "Asyncbaserequest";    /** Network connection timed out, default value is 10 seconds */protected int connecttimeout = 10 * 1000;    /** network Data read timeout, default value is 10 seconds */protected int readtimeout = 10* 1000; PriVate Boolean interrupted;    public Boolean isinterrupted () {return interrupted;    The public void setinterrupted (Boolean interrupted) {this.interrupted = interrupted;    } protected void Setconnecttimeout (int connecttimeout) {this.connecttimeout = ConnectTimeout;    } protected void Setreadtimeout (int readtimeout) {this.readtimeout = ReadTimeout;    } protected String Requesturl;    Protected map<string, string> parameter;    Private Parsecallback Parsehandler;    Private Resultcallback requestcallback;    protected HttpURLConnection Mhttpurlconn;    protected String Minstream;    Private MyException ex; Public asyncbaserequest (String URL, map<string, string> parameter, Parsecallback handler, Resultcallback        Requestcallback) {This.parsehandler = handler;        This.requesturl = URL;        This.parameter = parameter;    This.requestcallback = Requestcallback; /** * Send Network request * @return The InputStream returned by the network requestData Flow * @throws Exception */protected abstract String Getrequestresult () throws Exception;            @Override public void Run () {if (interrupted) {logutil.i (TAG, "Break the business processing thread before accessing the network (termination)");        Return            try {//access the network, get to return data Minstream = Getrequestresult ();                if (minstream! = null) {Object obj = null;                if (Parsehandler! = null) {//Callback data parsing Interface obj = Parsehandler.parse (minstream);                          } if (Requestcallback!=null) {requestcallback.onsuccess (obj);                }} else {LOGUTIL.E (TAG, "Get InputStream by HttpURLConnection return result is NULL."); ex = new MyException (R.string.network_request_fail, Constant.network_request_retun_null, R.string.network_req                Uest_return_null); Requestcallback.onfail (ex); The network request returned null}}catch (soCkettimeoutexception e) {//sockettimeoutexception This timeout exception is a description of the request has reached the server, the return data process timed out, if the order class request to be aware of, need to prevent duplicate commit E            x = new MyException (e); Requestcallback.onfail (ex);} catch (Connecttimeoutexception e) {//connecttimeoutexception This is a connection exception (such as not opening the network at all), the data has not arrived at the server, so it is not related to the Order class,            ex = new MyException (e) can be submitted again; Requestcallback.onfail (ex);}            catch (TimeoutException e) {//timeoutexception This is the total timeout exception, here is the catch of ex = new MyException (e); Requestcallback.onfail (ex); Io exception ID}catch (httphostconnectexception e) {//httphostconnectexception This exception occurs, check whether the program adds network permissions ex = new Myexcepti            On (e); Requestcallback.onfail (ex);}            catch (IOException e) {ex = new myexception (e); Requestcallback.onfail (ex);            IO exception identifier} catch (Exception e) {ex = new myexception (e); Requestcallback.onfail (ex); Unknown exception Identifier}} public HttpURLConnection Getrequestconn () {return MhttpurLconn; }}

Of course, two interfaces are required

Package Com.clxu.netframe.net.callback;import org.json.jsonexception;/*** * @function The data resolution interface returned by the network request  * @author CLXU * 2014-11-25 */public interface Parsecallback {    /**     * Parse the data returned by the network request     * @param json  string to parse, JSON format c5/>* @return Parsing Results     * @throws jsonexception JSON exception (when an ordinary string is converted to a JSON string, the format error throws the exception)     */public Object Parse (string JSON) throws jsonexception;}

Package Com.clxu.netframe.net.callback;import com.clxu.netframe.exception.myexception;/** * Function Description: The result of a network request returned callback interface * <span style= "font-family:arial, Helvetica, Sans-serif;" > @author clxu</span> * Date Created: 2014-11-19 */public interface Resultcallback {public    void onsuccess (Object obj );    public void Onfail (MyException e);


Frame Source:http://download.csdn.net/detail/brightshadow11111/8228287



Complimentary HttpClient and httpurlconnection Light Network-"thread pool introduction and network Request Flow"

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.