ndroid中网络请求一般使用Apache HTTP Client或者采用HttpURLConnect,但是直接使用这两个类库需要写大量的代码才能完成网络post和get请求,而使用android-async-http这个库可以大大的简化操作。
今天要介绍的是一个在Android上同样强大的网络请求库android-async-http(官方网址:https://loopj.com/android-async-http/ )
其主要特征如下:
1.处理异步Http请求,并通过匿名内部类处理回调结果
2.Http请求均位于非UI线程,不会阻塞UI操作
3.通过线程池处理并发请求
4.处理文件上传、下载
android-async-http实现下载
添加依赖:
dependencies {
compile 'com.loopj.android:android-async-http:1.4.9'
}
导入http包:
import com.loopj.android.http.*;
之后我推荐用官方网站上推荐的那个方法,回省很多工作量:
建立一个静态的Http客户端:在这个例子中,我们将使用静态访问器创建一个http客户端类,以便与Twitter的API进行通信。
import com.loopj.android.http.*;
/**
* Created by Administrator on 2018/4/10/010.
*/
public class HttpUtil {
private static final String BAse_url = "http://192.168.1.105:8890/type/jason/action/";
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(android.content.Context context, java.lang.String url, cz.msebera.android.httpclient.HttpEntity entity, java.lang.String contentType, ResponseHandlerInterface responseHandler) {
client.post(context,getAbsoluteUrl(url), entity, contentType,responseHandler);
}
private static String getAbsoluteUrl(String url) {
return BAse_url + url;
}
}
这样就可以很容易地在代码中使用api:
RequestParams requestParams = new RequestParams();
requestParams.put("username", "admin");
HttpUtil.get("getSensor", requestParams, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
Log.e("dqwqwfsdgsdg", responseString + "...");
}
});
AsyncHttpClient进行Json的Post请求:
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Buzzer", 1);
} catch (JSONException e) {
e.printStackTrace();
}
ByteArrayEntity entity = null;
try {
entity = new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpUtil.Post(mContext, "control", entity, "application/json", new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
Log.e("rs", response.toString());
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
}
});
里面的 HttpUtil是上面我写的一个静态的Http客户端。
也可直接创建一个新AsyncHttpClient实例并发出请求::
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onStart() {
// called before request is started
}
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
@Override
public void onRetry(int retryNo) {
// called when request is retried
}
});