一个基于回调的AndroidHTTP客户端库
dependencies {
compile 'com.loopj.android:android-async-http:1.4.9'
}
public class HttpUtil {
private static final String BASE_URI="http://192.168.1.105:8890/type/jason/action/";
private static AsyncHttpClient client=new AsyncHttpClient();//创建一个实例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;
}
}
HttpUtil.get("control", 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");
}
});
这种方式自定义post的参数的格式,一般使用json解析数据,此时就不需要刚刚创建的HttpUtil类了,直接在MainActivity中进行操作
AsyncHttpClient client = new AsyncHttpClient();//创建一个实例AsyncHttpClient:
final String url = "http://192.168.1.105:8890/type/jason/action/control";//获取接口文件地址
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("Buzzer","1");//接口文件中{'Buzzer':1}为一个整体,以下同理
jsonObject.put("Roadlamp","1");
jsonObject.put("Blower","1");
jsonObject.put("WaterPump","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();
}
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);//获取成功时log为{ 'result':'ok'},等待一会仪器将会产生效果
}
});
部分源代码参考GitHub,地址为https://github.com/loopj/android-async-http
第二种方式部分源代码参考另一篇文章,地址为https://blog.csdn.net/u013592964/article/details/51355507