我们可以先去github网站,搜索asynchttpclient,点击第一篇文章。
具体步骤如下:
1.首先在gradle.app文件里面添加一个包,记得Syno now 一下。
compile 'com.loopj.android:android-async-http:1.4.9'
2.其次我们需要在Mainnifest.xml中添加权限:
<uses-permission android:name="android.permission.INTERNET" />
3.发送数据
发送数据的方式有两种get方法和post方法
首先来看一下get方法:
public class Httpurl {
private static final String BASE="http://192.168.1.105:8890/type/jason/action/";
private static AsyncHttpClient asyncHttpClient=new AsyncHttpClient();
public static void get(String url, RequestParams requestParams, AsyncHttpResponseHandler asyncHttpResponseHandler){
asyncHttpClient.get(getAbsoluteUrl(url),requestParams,asyncHttpResponseHandler);
}
private static String getAbsoluteUrl(String url){
return BASE+url;
}
}
final RequestParams requestParams=new RequestParams();
requestParams.put("username","airHumidity");//传入值
Httpurl.get("getSensor",requestParams, new TextHttpResponseHandler() {
@Override //回调方法
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Toast.makeText(Main2Activity.this, "shibai", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Toast.makeText(Main2Activity.this, responseString, Toast.LENGTH_SHORT).show();
}
});
4.再来看一下post方法,用来实现json数据发送
AsyncHttpClient client=new AsyncHttpClient();
JSONObject jsonObject=new JSONObject();
try {
jsonObject.put("Blower",0);
jsonObject.put("WaterPump",0);
jsonObject.put("Roadlamp",0);
jsonObject.put("Buzzer",0);
} catch (JSONException e) {
e.printStackTrace();
}
ByteArrayEntity entity = null;
//105
String url="http://192.168.1.101:8890/type/jason/action/control/";
try {
entity=new ByteArrayEntity(jsonObject.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
http://192.168.1.105:8890/type/jason/action/control/{'Buzzer':1}
client.post(Main2Activity.this,url,entity,"application/json",new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.e("s", "onSuccess: "+response.toString() );
Toast.makeText(Main2Activity.this, response.toString(), Toast.LENGTH_SHORT).show();
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
Log.e("s", "onSuccess: "+responseString.toString() );
Toast.makeText(Main2Activity.this, responseString.toString(), Toast.LENGTH_SHORT).show();
}
});