Android Async Http Client一看名字就知道它是基于Http Client的,但是呢在安卓中Http Client已经废弃了,所以也不建议使用这个库了。然后仍然有一些可取的内容值得学习,所以这里也介绍一下。
官网:https://github.com/loopj/android-async-http
特点
用法
package cn.edu.zafu.http;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
/**
* Created by lizhangqu on 2015/5/7.
*/
public class TestClient {
private static final String BASE_URL = "http://121.41.119.107/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
参数通过RequestParams传递,没有参数则传递null
RequestParams params = new RequestParams();
params.put("","");
PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
client.setCookieStore(myCookieStore);
之后请求所得到的cookie都会自动持久化
如果要自己添加cookie,则调用以下代码
BasicClientCookie newCookie = new BasicClientCookie("cookiesare", "awesome");
newCookie.setVersion(1);
newCookie.setDomain("mydomain.com");
newCookie.setPath("/");
myCookieStore.addCookie(newCookie);
private void get(){
TestClient.get("test/index.php", null, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
}
private void post(){
RequestParams params = new RequestParams();
params.put("user","asas");
params.put("pass","12121");
params.put("time","1212121");
TestClient.post("test/login.php", 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) {
}
});
}
以上代码参考了Android Asynchronous Http Client官方实例
android开源框架android-async-http使用
android-async-http框架库使用基础
android-async-http框架库使用入门