网络_AsyncHttpClient_使用方法和代码

AsyncHttpClient的简单程度,让人感到呕吐。灰常简单。
//AsyncHttpClient is an open-source project made by developers for developers!


An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries.
All requests are made outside of your app’s main UI thread, but any callback logic will be executed on 
the same thread as the callback was created using Android’s Handler message passing. You can also
use it in Service or background thread, library will automatically recognize in which context is ran.


各种对响应体的包装处理回调类: 
AsyncHttpResponseHandler;
BaseJsonHttpResponseHandler;
BinaryHttpResponseHandler;
DataAsyncHttpResponseHandler;
FileAsyncHttpResponseHandler;
JsonHttpResponseHandler;




// get 请求   类似post请求,类似上传加入RequestParams。
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://www.google.com", new AsyncHttpResponseHandler() {
    public void onStart() {}
    public void onSuccess(int statusCode, Header[] headers, byte[] response) {}
    public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {}
    public void onRetry(int retryNo) {}
});




//官方推荐配置。
public class TwitterRestClient {
  private static final String BASE_URL = "https://api.twitter.com/1/";
  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(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
      client.post(getAbsoluteUrl(url), params, responseHandler);
  }
  private static String getAbsoluteUrl(String relativeUrl) {
      return BASE_URL + relativeUrl;
  }
}





//上传。文件上传 加入post中。
//输入流上传
InputStream myInputStream = blah;
RequestParams params = new RequestParams();
params.put("secret_passwords", myInputStream, "passwords.txt");
//本件上传。可以多个文件
File myFile = new File("/path/to/file.png");
RequestParams params = new RequestParams();
params.put("profile_picture", myFile);
//二进制字节流上传
byte[] myByteArray = blah;
RequestParams params = new RequestParams();
params.put("soundtrack", new ByteArrayInputStream(myByteArray), "she-wolf.mp3");





//下载
AsyncHttpClient client = new AsyncHttpClient();
client.get(new File("存储的位置"), new FileAsyncHttpResponseHandler(/* Context */ this) {
    @Override
    public void onSuccess(int statusCode, Header[] headers, File response) {
        // Do something with the file `response`
    }
});



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值