Android Network connection tool Best optimization

Source: Internet
Author: User

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

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.