AsyncHttpClient的用法

一、引入依赖包:

dependencies {

compile 'com.loopj.android:android-async-http:1.4.9'

}

二、最简单用法:

公共类HTTPURL:

 public class Httpurl {
    private static final String BASE_URL = "http://192.168.1.101:8890/type/jason/action/";
    private static AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
        asyncHttpClient.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) {
        asyncHttpClient.get(context,getAbsoluteUrl(url), entity,contentType, responseHandler);
    }
    private static String getAbsoluteUrl(String relativeUrl) {
        return BASE_URL + relativeUrl;
    }
 
  

AsyncHttpClient client = new AsyncHttpClient();

client.get("https://www.csdn.net/", new TextHttpResponseHandler() {

@Override

public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable)

{

}

@Override

public void onSuccess(int statusCode, Header[] headers, String responseString) {

}

});

三、传递简单参数:

 RequestParams requestParams=new RequestParams();
//                requestParams.put("params","{\"classify_id\":70,\"page\":1,\"page_count\":2}");

             Httpurl.get("getContorllerStatus",requestParams, new TextHttpResponseHandler() {
                 @Override
                 public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                     Toast.makeText(WangluoActivity.this, "faile", Toast.LENGTH_SHORT).show();
                 }


                 @Override
                 public void onSuccess(int statusCode, Header[] headers, String responseString) {
                     Toast.makeText(WangluoActivity.this, responseString, Toast.LENGTH_SHORT).show();
                 }

});

四、传递JSON格式参数:

JSONObject jsonObject = new JSONObject();
try {
    jsonObject.put("Roadlamp",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();
}

Httpurl.post(this,"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);
    }
});

 
  

你可能感兴趣的:(andriod)