Package Com.jia.httputiltools;public interface Httpcallbacklistener {void onfinish (String response); void OnError ( Exception e);}
Package Com.jia.httputiltools;import Java.io.bufferedreader;import Java.io.inputstream;import Java.io.inputstreamreader;import java.net.httpurlconnection;import java.net.url;/** * @author 姚文天 * */public class httputil {public static void Sendhttprequest (final String address,final Httpcallbacklistener listener) {New Thread (new Ru Nnable () {@Overridepublic void run () {httpurlconnection connection = null;try {URL url = new URL (address); connection = (Ht tpurlconnection) url.openconnection (); Connection.setrequestmethod ("GET"); Connection.setconnecttimeout (8000); Connection.setreadtimeout (8000); Connection.setdoinput (true); Connection.setdooutput (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) {//Callback OnFinish () method Listener.onfinish (Response.tostring ());}} catch (Exception e) {if (listEner! = null) {//Callback OnError () method Listener.onerror (e);}} finally {if (connection! = null) {Connection.disconnect ();}}}). Start ();}}
Package Com.jia.httputiltools;import Android.app.activity;import Android.os.bundle;public class MainActivity extends Activity {String address = "http://blog.csdn.net/fang323619"; @Overrideprotected void OnCreate (Bundle Savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); Httputil.sendhttprequest (Address, new Httpcallbacklistener () {@Overridepublic void OnFinish (String response) {// Here the specific logic is executed based on the return content} @Overridepublic void OnError (Exception e) {//Where the exception is handled}});}
Android Network connection tool Best optimization