Processing of Android timeout mechanism (very good)

Source: Internet
Author: User
Tags response code

Due to the response of Mobile Phone applications, there was a great correlation with the current situation of wireless communication networks. However, communication networks often have the characteristics of instability and long latency. Therefore, in our applications, the timeout mechanism is particularly important when we request the network.

Timeout mechanisms include:

1. http request timeout Mechanism

2. Socket Communication timeout Mechanism

HTTP request timeout Mechanism

public static void main(String[] args){long a=System.currentTimeMillis();try{URL myurl = new URL(“http://www.baidu.cn”);URLConnection myurlcon = myurl.openConnection();myurlcon.setConnectTimeout(1000);myurlcon.setReadTimeout(1000);BufferedReader in = new BufferedReader(new InputStreamReader(myurlcon.getInputStream(),”UTF-8″));String inputLine;while ((inputLine = in.readLine()) != null){System.out.println(inputLine);in.close();System.out.println(System.currentTimeMillis()-a);}} catch (MalformedURLException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}

If the timeout occurs, the following exception is thrown.

Java.net. sockettimeoutexception: Read timed out
At java.net. socketinputstream. socketread0 (native method)
At java.net. socketinputstream. Read (fig. Java: 129)
At java. Io. bufferedinputstream. Fill (bufferedinputstream. Java: 218)
At java. Io. bufferedinputstream. read1 (bufferedinputstream. Java: 256)
At java. Io. bufferedinputstream. Read (bufferedinputstream. Java: 313)
At sun.net. www.http. httpclient. parsehttpheader (httpclient. Java: 606)
At sun.net. www. http. httpclient. parsehttp (httpclient. Java: 554)
At sun.net. www. Protocol. http. httpurlconnection. getinputstream (httpurlconnection. Java: 940)
At com. Test. Main (test. Java: 52)

There is also an article about it better:

In the android project, if an HTTP request is used, the timeout management and exception management of the HTTP request must also be added. In this case, a bunch of requests are found on Google, however, it is relatively simple to write, and it is okay to make a demo, which is not perfect in the project. I wrote an example myself. You are welcome to correct it.

Note: There are three aspects

How to control the timeout Mechanism

How to handle exceptions

How to handle request errors

Private class xmlasyncloader extends xmlresourcerequest {private Boolean miscancle = false; private httpget mget; private httpclient mhttp; Public xmlasyncloader (mxactivity <?> Activity, string URL) throws malformedurlexception {super (activity, URL) ;}@ override protected void dotaskinbackground () {// request data if (murl. tolowercase (). startswith ("http: //") {mget = inithttpget (murl); mhttp = inithttp (); try {httpresponse response = mhttp.exe cute (mget); If (miscancle) {return;} If (response! = NULL) {If (response. getstatusline (). getstatuscode ()! = Httpstatus. SC _ OK) {onresponseerror ("network error"); log. V (TAG, "the code is:" + response. getstatusline (). getstatuscode (); return;} policyupdateprogress (70); document DOC = getdocumet (response); element root = Doc. getdocumentelement (); nodelist applist = root. getelementsbytagname (item_element_name); Final int Len = applist. getlength (); If (LEN <= 0) {// No items onfoundnoitems (); Return ;}for (INT I = 0; I <Len; I ++) {element item = (element) applist. item (I); If (item. getnodetype () = node. element_node) {hahaiteminfo info = createhahaitemino (item); If (miscancle) {return;} onfounditem (Info, 80 + 20 * (I + 1)/Len); addurltoqueue (info. usericonurl) ;}}}catch (connecttimeoutexception e) {onresponseerror ("time out") ;}catch (clientprotocolexception e) {-- mcurrentpage; E. printstacktrace ();} catch (ioexception e) {-- mcurrentpage; E. printstacktrace ();} catch (xmlpullparserexception e) {-- mcurrentpage; E. printstacktrace () ;}finally {policyloadfinish (); policyloadimages (); mhttp. getconnectionmanager (). shutdown () ;}} private httpclient inithttp () {httpclient client = new defaulthttpclient (); client. getparams (). setintparameter (httpconnectionparams. so_timeout, time_out_delay); // timeout setting client. getparams (). setintparameter (httpconnectionparams. connection_timeout, time_out_delay); // return client connection timeout;} private httpget inithttpget (string murl) {httpget get = new httpget (murl); initheader (get); return get ;} @ override public Boolean trycancel () {log. I (TAG, "trycanle is working"); mget. abort (); miscancle = true; mhttp. getconnectionmanager (). shutdown (); notifyloadfinish (); Return true ;}}

This is an asynchronous task class. It sends GET request data, parses server response data, and notifies the UI thread to update the UI.

In Android, there are many ways to write internet interactions. You can use the packages provided by Apache or the APIS provided by Google. I don't know which one is better, but I am used to using it.
Apache API.
1. Set the timeout Mechanism
Client. getparams (). setintparameter (httpconnectionparams. so_timeout, timeout); // timeout setting client. getparams (). setintparameter (httpconnectionparams. connection_timeout, time_out_delay); // connection timeout

Two timeout methods are set here. The first is request timeout and the second is connection timeout.

When a request is sent to the server, the request establishes a socket connection with the server, but no socket connection is established for a long time. In this case, the first request times out. This occurs mainly in the request.
A non-existent server. An interruptedioexception is thrown after the timeout.
Timeout for blocking operations. The argument value is specified in milliseconds.InterruptedioexceptionIs thrown if this timeout expires.
The client has established a socket connection with the server, but the server does not process the client's requests and does not have the corresponding server. This is the second connection timeout. Timeout will throw
Connecttimeoutexception exception. connecttimeoutexception inherits from interruptedioexception, so you only need to capture connecttimeoutexception.
2. Analyze the request process
2.1 httpresponse response = mhttp.exe cute (mget );
Execute the request method to obtain the server response. (here we have an immature view. response cannot be null and remains to be verified ).
2.2 GET request response code
If (response. getstatusline (). getstatuscode ()! = Httpstatus. SC _ OK) {onresponseerror ("network error"); log. V (TAG, "the code is:" + response. getstatusline (). getstatuscode (); return ;}
Even if the server is connected and the data is obtained from the server, the error message returned by the server may be returned. Therefore, special processing is required.
2.3 Exception Handling
For exceptions, it cannot be simply captured. For example, in the code above, I request data on the third page. If an exception occurs, the request fails, then I need to roll back the current page number,
If it succeeds, you do not need to roll back, so you need to handle the exception.
2.4 Finally keywords
The link must be closed whether the request is successful or fails.

Blog reposted from liudroid

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.