Fault Tolerance management for HTTP requests in Android

Source: Internet
Author: User

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 lot 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 ;
}
Notifyupdateprogress ( 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 {
Notifyloadfinish ();
Notifyloadimages ();
Mhttp. getconnectionmanager (). Shutdown ();
}

}
}


Private Httpclient inithttp (){
Httpclient Client = New Defaulthttpclient ();
Client. getparams (). setintparameter (
Httpconnectionparams. so_timeout, time_out_delay ); // Timeout settings
Client. getparams (). setintparameter (
Httpconnectionparams. connection_timeout, time_out_delay ); // Connection timeout
Return Client;
}

Private Httpget inithttpget (string murl ){
Httpget = 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, time_out_delay );//Timeout settings
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. After timeoutInterruptedioexception.
 
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
You can.
 
2. Analyze the request process
 
2.1Httpresponse 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, you cannot simply catch them. For exampleCode,
 
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.
 

 

 

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.