Android Open source Framework android-async-http use

Source: Internet
Author: User
Tags ustring

1. new project, go to the official website to download the zip package, unzip, open the releases file, put the latest jar package, test into the Project Libs directory, the introduction of the package.

2. Through 1, it can be used , very simple , the following is a demo of their own, using it to provide a variety of different methods to complete from the server to obtain a JSON data:


Package Com.http;import Com.loopj.android.http.asynchttpclient;import Com.loopj.android.http.asynchttpresponsehandler;import Com.loopj.android.http.binaryhttpresponsehandler;import Com.loopj.android.http.jsonhttpresponsehandler;import Com.loopj.android.http.RequestParams;    public class Httputil {private static asynchttpclient client =new asynchttpclient ();   Instance Session object static {Client.settimeout (11000); Sets the link timeout, if not set, defaults to 10s} public static void Get (String urlstring,asynchttpresponsehandler res)//Get a strin with a full URL    G Object {client.get (urlstring, RES); public static void Get (String urlstring,requestparams params,asynchttpresponsehandler res)//url with parameter {C    Lient.get (urlstring, params,res); public static void Get (String urlstring,jsonhttpresponsehandler res)//without parameters, get JSON object or array {client.get (URL    String, RES); public static void Get (String urlstring,requestparams params,jsonhttpresponsehandler res)//with parameters, get JSon object or array {client.get (urlstring, params,res); The public static void get (String ustring, Binaryhttpresponsehandler bhandler)//download data is used, which returns the byte data {client.ge    T (ustring, Bhandler);    } public static Asynchttpclient Getclient () {return client; }}


This class mainly lists the get methods that we commonly use, and where we want to go, we can call the class.

Specific classes to use:

Package com.http; Import Java.io.file;import Java.io.FileOutputStream; Import Org.json.jsonarray;import Org.json.JSONObject; Import Android.app.activity;import Android.app.progressdialog;import Android.os.bundle;import Android.os.environment;import Android.util.log;import Android.view.view;import Android.widget.TextView;import Android.widget.Toast; Import Com.loopj.android.http.asynchttpresponsehandler;import Com.loopj.android.http.BinaryHttpResponseHandler; Import Com.loopj.android.http.jsonhttpresponsehandler;import com.loopj.android.http.RequestParams; public class Mainactivity extends Activity {private TextView TextView;//Top TextView private ProgressDialog Pdialog    ; Private TextView textView2; The following textview shows all data obtained @Override protected void onCreate (Bundle savedinstancestate) {super.oncreate (Savedin        Stancestate);        Setcontentview (R.layout.activity_main);        TextView = (TextView) Findviewbyid (R.id.text); TextView2 = (TextView) Findviewbyid (r.id. Text2);        public void method1 (view view) {Pdialog = Progressdialog.show (This, "Please Wait", "data Loading"); String urlstring = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&p=2&size=10"; A URL address for the recipe Httputil.get (urlstring, New Asynchttpresponsehandler () {public void onsuccess (String ar                G0) {//Fetch data successfully will be called here Pdialog.dismiss ();                Textview.settext ("Get JSON data successfully, see below");                Textview2.settext (arg0);            LOG.I ("Hck", arg0);            };                        public void OnFailure (Throwable arg0) {//failed, call Toast.maketext (Mainactivity.this, "OnFailure",            Toast.length_long). Show ();            };        public void OnFinish () {//After completion of call, failure, success, all fall off};    });        } public void Method2 (view view) {String urlstring = "http://client.azrj.cn/json/cook/cook_list.jsp?"; Requestparams params = new Requestparams (); Binding parameter Params.put ("type", "1");        Params.put ("P", "2");        Params.put ("Size", "10"); Httputil.get (urlstring, params, new Jsonhttpresponsehandler () {public void onsuccess (Jsonarray arg0) {//successful return                Back to a Jsonarray data log.i ("Hck", arg0.length () + ""); try {textview.settext ("recipe name:" + arg0.getjsonobject (2). getString ("name"));                    /return Jsonarray, get the 2nd Jsonobject object in the Jsonarray data, and get the data value named name} catch (Exception e) {                LOG.E ("Hck", e.tostring ());            }            };            public void OnFailure (Throwable arg0) {log.e ("Hck", "onfailure" + arg0.tostring ());            };            public void OnFinish () {log.i ("Hck", "onfinish");            };                public void onsuccess (Jsonobject arg0) {//returns Jsonobject, which is called here log.i ("Hck", "onsuccess");                       try {textview.settext ("recipe Name:")     + Arg0.getjsonarray ("list"). Getjsonobject (0). getString ("name"));                } catch (Exception e) {log.e ("Hck", e.tostring ());        }            };    }); } public void Method3 (view view) {String urlstring = "http://client.azrj.cn/json/cook/cook_list.jsp?type=1&        P=2&size=10 ";                Httputil.get (urlstring, New Jsonhttpresponsehandler () {public void onsuccess (Jsonobject arg0) {                                     try {textview.settext ("recipe name:" + arg0.getjsonarray ("list"). Getjsonobject (1)                . getString ("name"));                } catch (Exception e) {log.e ("Hck", e.tostring ());        }            };    });        } public void Method4 (view view) {String urlstring = "http://client.azrj.cn/json/cook/cook_list.jsp?";        Final Requestparams params = new Requestparams (); Params. put ("type", "1");        Params.put ("P", "2");        Params.put ("Size", "10");                Httputil.get (urlstring, params, new Asynchttpresponsehandler () {public void onsuccess (String arg0) {                    try {jsonobject jobject = new Jsonobject (arg0);                                    Textview.settext ("Recipe name:" + jobject.getjsonarray ("list"). Getjsonobject (2)                    . getString ("name"));                LOG.I ("Hck", Params.getentity (). toString ());        } catch (Exception e) {}};    }); } public void Method5 (view view) {String URL = "http://f.hiphotos.baidu.com/album/w%3D2048/sign=38c43ff7902397d        Dd6799f046dbab3b7/9c16fdfaaf51f3dee973bf7495eef01f3b2979d8.jpg ";                Httputil.get (URL, new Binaryhttpresponsehandler () {@Override public void onsuccess (byte[] arg0) {                Super.onsuccess (arg0); File File = Environment.gEtexternalstoragedirectory ();                File File2 = new file (file, "cat");                File2.mkdir ();                File2 = new File (file2, "cat.jpg");                    try {fileoutputstream oStream = new FileOutputStream (file2);                    Ostream.write (arg0);                    Ostream.flush ();                    Ostream.close ();                Textview.settext ("Cute kitty has been saved in SDcard");                    } catch (Exception e) {e.printstacktrace ();                LOG.I ("Hck", e.tostring ());    }            }        }); }}
<scrollview xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "vertical" android:gravity= "center_horizontal" > <linearlayout android:layout_width= "Fill_paren    T "android:layout_height=" fill_parent "android:orientation=" vertical "android:gravity=" center_horizontal ">     <textview android:textcolor= "#FF0000" android:textsize= "16sp" android:layout_margintop= "20DP" Android:gravity= "Center_horizontal" android:id= "@+id/text" android:layout_width= "Wrap_content" Andro    id:layout_height= "Wrap_content" android:text= "Get data will be displayed here"/><button android:layout_margintop= "50DP"     Android:id= "@+id/bt1" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "First Kind" android:onclick= "Method1"/><buttOn android:id= "@+id/bt2" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" Android:text    = "2nd type" android:onclick= "Method2"/><button android:id= "@+id/bt3" android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:text= "3rd type" android:onclick= "method3"/><button android:id = "@+id/bt4" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "4th type" Android oid:onclick= "METHOD4"/><button android:id= "@+id/bt5" android:layout_width= "Wrap_content" android:layout _height= "Wrap_content" android:text= "5th Type" android:onclick= "Method5"/> <textview Android:textcolo        R= "#FF0000" android:textsize= "16sp" android:layout_margintop= "20DP" android:gravity= "Center_horizontal"         Android:id= "@+id/text2" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" /></linearlayouT></scrollview> 



Android Open source Framework android-async-http use

Related Article

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.