An HTTP request is a time-consuming operation that, if placed on the main thread, causes the UI thread to block, and Android does not allow the developer to place the network time-consuming operation on the main thread after API8. For an open thread to make an HTTP request, the data returned from the server requires the main thread to process and update the UI, The child thread cannot update the UI, so there is a connection between the child thread and the main thread. Android provides a handler message processing mechanism to implement thread communication, and the child thread notifies the primary thread of the network return result by sending a message, the main thread receives the message, processes the data, and makes UI operations. This enables the entire client to send a request to the server and receive requests to process the request. For sub-threading design, it is recommended to take a thread template design approach. The steps are as follows
First, customize the template thread, inherit the thread class, set it to abstract class, as the parent of the specific thread
Public abstract class Basethread extends Thread {
protected String Requesturl;
protected Map Resultmap;
protected Map requestparams;
protected List resultlist;
protected Handler Mhandler;
protected Message msg;
protected String Stateid;
/**
* Handler is the interaction class about the main thread
* Stateid is the identification number of the message with the main thread
*
* @param Mhandler
* @param Stateid
*/
Stateid used as a label for message
Public Basethread (Handler Mhandler, String Stateid) {
This.mhandler = Mhandler;
This.stateid = Stateid;
}
Next, design a method to initialize the URL of the HTTP specific request, and the request parameters
/**
* Set the parameters of the post form and the location of the requesting host
*
* @param requesturl
* @param requestparams
*/
public void Setrequestprepare (String requesturl, Map requestparams) {
This.requesturl = Requesturl;
This.requestparams = Requestparams;
}
Then, a method is designed to get the string from the server to the processed map table, which is the main thread service.
/**
* Gets the returned result, the result is in map form
*
* @return
*/
Public Map Getresultmap () {
if (this.resultmap! = null) {
return (THIS.RESULTMAP);
} else {
This.resultmap = new HashMap ();
return (THIS.RESULTMAP);
}
}
Design a method to determine whether the request is successful or not
/**
* Based on the string returned by the Httputils class to determine whether the request succeeded or failed
* @param str
* @return
*/
Protected Boolean dealrequeststate (String str) {
if (str! = null) {
if (Str.equals ("Paramsexception")) {
return (false);
} else if (Str.equals ("Singletonexception")) {
return (false);
} else if (Str.equals ("Internetexception")) {
return (false);
} else if (Str.equals ("Switchexception")) {
return (false);
} else {
return (true);
}
} else {
LOG.I ("LZW", "null");
return (false);
}
}
Then, design a method to hold the message of the network status
/**
* Notice the status of the mainline preempted
*
* @param key
* @param state
*/
protected void Setloadstate (String key, int state) {
this.msg = new Message ();
BUNDLE BD = new bundle ();
Bd.putint (key, state);
This.msg.setData (BD);
}
This method is used to check the request parameters
protected void Checkrequestmap ()
{
Iterator It=this.requestparams.entryset (). Iterator ();
while (It.hasnext ())
{
Map.entry<string,string> entry= (map.entry<string,string>) it.next ();
LOG.I ("LZW", Entry.getkey ());
LOG.I ("LZW", Entry.getvalue ());
}
}
Finally, to implement the Run method
/**
* The main thread-body method, first requesting the server,
* Give the returned result (character) of the server to the instantiated method of the subclass
*/
public void Run () {
This.checkrequestmap ();
LOG.I ("LZW", "url=" +this.requesturl);
try {
The previous article used to implement sending HTTP requests httputils
Implements the Send request method, and the request parameters and paths are initialized by the main thread by calling the Setrequestprepare method.
Httputils executes the Requesthttpsever method to get the return string stored in the variable responsestr
String Responsestr =
Httputils.requesthttpserver (This.requesturl, This.requestparams,
Comparameter.encode_utf_8, Comparameter.encode_utf_8);
By calling the Dealrequeststate function to determine the server connection state, the incoming parameter returns a string to the server
if (!this.dealrequeststate (RESPONSESTR)) {
Failed to return success, save error message
This.setloadstate (This.stateid, comparameter.state_error);
Sends the error message to the main thread, to the main thread handler processing
This.mHandler.sendMessage (THIS.MSG);
Return
}
If the returned string is normal, the returned character is processed and stored as a map, which is an abstract method, placed in a subclass.
This.dealreponsestring (RESPONSESTR);
Tell the main thread to return to success
This.setloadstate (This.stateid, comparameter.state_right);
This.mHandler.sendMessage (THIS.MSG);
} catch (Exception e) {
This.setloadstate (This.stateid, comparameter.state_error);
This.mHandler.sendMessage (THIS.MSG);
E.printstacktrace ();
}
}
Methods that return strings are processed as abstract methods because different requests return a string that may not be the same, placed in the subclass processing
protected abstract void dealreponsestring (String responsestring) throws Exception;
Here is a subclass that inherits the thread template and processes the return string example
public class Firstloginrequestthread extends Basethread {
Public Firstloginrequestthread (Handler Mhandler, String Stateid) {
Super (Mhandler, Stateid);
}
protected void dealreponsestring (String responsestring) throws exception{
The Resultmap here is the Parent property, which is used to process the server return string, add content to the map of the parent class, and get the return parameter service for the main thread.
This.resultmap = new hashmap<string, string> ();
String tmparrstr[] = Responsestring.split (":");
if (tmparrstr[1].equals ("login")) {
String Tmparrstr1[]=tmparrstr[2].split ("[+]");
This.resultMap.put (Tmparrstr[0], tmparrstr[1]);
This.resultMap.put ("type", tmparrstr1[0]);
This.resultMap.put ("DataBaseId", tmparrstr[3]);
} else if (Tmparrstr[1].equals ("Unlogin")) {
This.resultMap.put (Tmparrstr[0], tmparrstr[1]);
This.resultMap.put ("Failreason", tmparrstr[2]);
}
LOG.I ("LZW", responsestring);
}
}
Thread action Design template for Android HTTP request