Optimal Android Network Connection Tool and android Network Connection
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 Yao WenTian **/public class HttpUtil {public static void sendHttpRequest (final String address, final HttpCallbackListener listener) {new Thread (new Runnable () {@ Overridepublic void run () {HttpURLConnection connection = nu Ll; try {URL url = new URL (address); connection = (HttpURLConnection) 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 StringBu Ilder (); 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) {// execute the specific logic here based on the returned content} @ Overridepublic void onError (Exception e) {// handle exceptions here }});}}