android-async-http Example

Source: Internet
Author: User
Tags ustring

This is my back to the Android, a new study of the android-async-http framework of the example, a simple introduction, but also a small note of their own to do an article


Let's introduce what it is.

First it is the third party open source class library, in the Android development, the request server obtains the data is too common, then it is solves the general request way the trouble place, simply, uses it, later requests the server to become simple

Second, look at the framework name with Async, experienced developers know that it is asynchronous, since it is asynchronous and used in Android, which means that it is used in non-UI threads. Another benefit is that you do not have to manually new thread threads, is not very good use of Satan.


Wipe, or on the code bar!

1, to the official website or any other place, download the jar package, or source code, all right, casually

2. Import the jar package into your project and build it, as


3. If you want to see the source code, the source Library\src\main\java com package paste into the project src directory, such as

4. Just write the main code. This is a util of the package

Package cn.com.asynchttp;


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 Httputill {


private static Asynchttpclient client = new Asynchttpclient ();//Instantiation of Object


static {
Client.settimeout (5000); Set connection timeout, default 10s
}


/**
* Get a String object with a full URL
*
* @param urlstring
* @param Res
*/
public static void Get (String urlstring, Asynchttpresponsehandler Res) {
Client.get (urlstring, RES);
}


/**
* URL with parameters
*
* @param urlstring
* @param params
* @param Res
*/
public static void Get (String urlstring, requestparams params, Asynchttpresponsehandler res) {
Client.get (urlstring, params, res);
}


/**
* Get JSON objects or arrays without parameters
* @param urlstring
* @param Res
*/
public static void Get (String urlstring, Jsonhttpresponsehandler Res) {
Client.get (urlstring, RES);


}


/**
* with parameters, get JSON object or array
* @param urlstring
* @param params
* @param Res
*/
public static void Get (String urlstring, requestparams params, Jsonhttpresponsehandler res) {


Client.get (urlstring, params, res);


}


/**
* Data will be returned with byte data when downloaded.
* @param ustring
* @param Bhandler
*/
public static void Get (String ustring, Binaryhttpresponsehandler bhandler) {


Client.get (ustring, Bhandler);


}


public static Asynchttpclient Getclient () {


return client;
}


}

And then there's the activity.


Package cn.com.asynchttp;


Import Org.apache.http.Header;
Import Org.apache.http.protocol.HTTP;


Import Com.loopj.android.http.AsyncHttpResponseHandler;
Import Com.loopj.android.http.RequestParams;


Import android.app.Activity;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import CN.COM.R;


/**
* Android-aysnc-http Framework Learning
*
* @author Administrator
*
*/
public class Studyactivity extends Activity {


@Override
protected void OnCreate (Bundle savedinstancestate) {
TODO auto-generated Method Stub
Super.oncreate (savedinstancestate);


Setcontentview (r.layout.studyasynchttp);


Button Btn_click = (button) Findviewbyid (R.id.btn_studyasynchttp_click);
Btn_click.setonclicklistener (New Onclicklistener () {


@Override
public void OnClick (View v) {


String url = "http://This is the address of my Project Server, this is not affixed";


Requestparams params = new Requestparams ();
Params.add ("Key", "value"); Here is the parameter, can use put also can use Add, casually
Params.add ("Key", "value");


Httputill.get (URL, params, new Asynchttpresponsehandler () {


@Override
public void onsuccess (int arg0, header[] arg1, byte[] arg2) {
TODO auto-generated Method Stub


System.out.println ("onsuccess-arg0--------" + arg0);
System.out.println (New String (ARG2));//This is the data returned by the server, this is no source,//surface is a source.


}


@Override
public void onfailure (int arg0, header[] arg1, byte[] arg2, Throwable arg3) {
TODO auto-generated Method Stub
System.out.println ("OnFailure---arg0--------" + arg0);
}
});

Httputill.get (URL, params, new Asynchttpresponsehandler () {

@Override
public void onsuccess (int statusCode, header[] headers, byte[] responsebody) {

}

@Override
public void onfailure (int statusCode, header[] headers, byte[] responsebody, throwable error) {

}
});
}
});


}


}


Layout file, a button

<?xml version= "1.0" encoding= "Utf-8"?>
<linearlayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent"
android:orientation= "Vertical" >


<button
Android:layout_width= "Fill_parent"
android:layout_height= "Wrap_content"
Android:id= "@+id/btn_studyasynchttp_click"
android:text= "Studysynchttp"
/>



</LinearLayout>


Search the Karma!


Below share next post,get, request way! Also refer to others, this does not matter!

/**
* Implemented using the Asynchttpclient post method
* @param userName
* @param userpass
*/
public void Httpclientpost (string userName, String userpass) {
Asynchttpclient client = new Asynchttpclient (); Create a client object for an asynchronous request
String url = "http://"; Define the requested address
To create a encapsulated object that requests parameters
Requestparams params = new Requestparams ();
Params.put ("username", username); Set the parameter name and parameter value of the request
Params.put ("Userpass", userpass);//Set parameter names and parameters for the request
Execute POST method
Client.post (URL, params, new Asynchttpresponsehandler () {
/**
* Methods of successful processing
* StatusCode: The status code of the response; Headers: The corresponding header information such as the response time, the response of the server;
* Responsebody: bytes of response content
*/
@Override
public void onsuccess (int statusCode, header[] headers,
Byte[] responsebody) {
if (StatusCode = = 200) {
Tv_result.settext (New String (responsebody)); Set the displayed text
}
}

/**
* Methods of failure handling
* ERROR: Response failure message encapsulated in this exception object
*/
@Override
public void onfailure (int statusCode, header[] headers,
Byte[] responsebody, throwable error) {
Error.printstacktrace ();//Print the error message to the track
}
});
}


GET

/**
* Implemented using Asynchttpclient's Get method
* @param userName
* @param userpass
*/
public void Httpclientget (string userName, String userpass) {
Creating an asynchronous client object
Asynchttpclient client = new Asynchttpclient ();

String url = "";//Requested address
To create a encapsulated object that requests parameters
Requestparams params = new Requestparams ();
Params.put ("username", username); Set the parameter name and parameter value of the request
Params.put ("Userpass", userpass);//Set parameter names and parameters for the request

When sending a GET request URL address corresponding parameter, anonymous callback object
Client.get (URL, params,new asynchttpresponsehandler () {
@Override
public void onsuccess (int statusCode, header[] headers,
Byte[] responsebody) {
Methods of successful Processing
System.out
. println ("StatusCode-------------------" + statusCode);
Traverse Header Information
for (int i = 0; i < headers.length; i++) {
Header header = Headers[i];
System.out.println ("header------------Name:"
+ header.getname () + ",--Value:"
+ Header.getvalue ());
}
Setting the contents of a control
Tv_result.settext (New String (responsebody));
}

@Override
public void onfailure (int statusCode, header[] headers,
Byte[] responsebody, throwable error) {
Methods of failure handling
Error.printstacktrace ();
}
});
}





Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

android-async-http Example

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.