/**
* HTTP Tool class (with Java fallback mechanism) [Note: UI update is still not possible, still in the sub-thread operation]
* When using HTTP for network interaction multiple times, it can be encapsulated in a class
* How to use:
* First to build an interface class: The following:
* Public Interface httpcallbacklistener{
*
* void OnFinish (String response)
*
* void OnError (Exception e)
*
* }
* Finally in the call class using
Following
*
*
* Httputil.sendhttpresquest (address,new Httpcallbacklistener () {
* @Override
* public void OnFinish (String response) {
*//here to handle return data operation logic
*
* }
*
* @Override
* Pubic void OnError (Exception e) {
*
*//here to deal with the abnormal situation
*
*}
* })
*
*
* (Java's callback mechanism is used to solve the problem when the server has not yet responded with the end of the execution ....) That is, the time problem, with a callback does not end the method)
*
*/
Public class httputil{
public static void Sendhttprequest (final String address,final Httpcallbacklistener Listener) {
New Thread (new Runnable () {
@Override
public void Run () {
HttpURLConnection connection = null; try{
URL url = new URL (address);
Connection = (httpurlconnection) url.openconnection ();
Connection.setrequestmethod ("GET");
Connection.setconnecttimeout (800);
Connection.setreadtimeout (8000);
Connection.setdoinput (TRUE);
Connection.setdoouput (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) {
Listener.onfinish (response.tostring ());
}
}catch (Exception e) {
Listener.onerror (e);
}finally{
if (connection! = null) {
Connection.disconnect ();
}
}
}
}). Start ();
}
}
Android HTTP Tool Encapsulation class