首先,在gradle里添加依赖:
compile 'com.loopj.android:android-async-http:1.4.9'
AsyncHttpClient特点:
使异步HTTP请求,处理响应。匿名回调
HTTP请求发生外部UI线程
请使用ThreadPool以并行使用资源帽
GET/POST访问
代码演示:
asynchttpclient的回调方法 :
第一步,创建实体类HttpUtil:
public class HttpUtil {
private static final String BASE_URI="http://192.168.1.105:8890/type/jason/action/";
private static AsyncHttpClient client=new AsyncHttpClient();
public static void get(String url, RequestParams requestParams, AsyncHttpResponseHandler asyncHttpResponseHandler){
client.get(getAbsoluteUrl(url),requestParams,asyncHttpResponseHandler);
}
private static String getAbsoluteUrl(String url){
return BASE_URI+url;
}
}
然后在MainActivity中回调方法:
RequestParams requestParams=new RequestParams();
requestParams.put("admin","airHumidity");
HttpUtil.get("getSensor", requestParams, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(MainActivity.this, "获取网络权限失败", Toast.LENGTH_SHORT).show();
Log.e("MainActivity","222222222222222222222222");
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(MainActivity.this, responseString, Toast.LENGTH_SHORT).show();
Log.e("MainActivity","11111111111111111111111111111111");
}
});
asynchttpclient的post方法发送json参数 :
AsyncHttpClient client = new AsyncHttpClient();
final String url = "http://192.168.1.105:8890/type/jason/action/control";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Roadlamp",0);
} 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();
}
client.post(MainActivity.this,url,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);
}
});