美文网首页
android-async-http库的使用

android-async-http库的使用

作者: JeremyDai | 来源:发表于2016-06-05 09:55 被阅读855次

    介绍

    android中网络访问的第三方库github 地址:https://github.com/loopj/android-async-http
    android-async-http主页:http://loopj.com/android-async-http/

    特性

    • 发送异步http请求,在匿名callback对象中处理response信息;
    • http请求发生在UI(主)线程之外的异步线程中;
    • 内部采用线程池来处理并发请求;
    • 通过RequestParams类构造GET/POST;
    • 内置多部分文件上传,不需要第三方库支持;
    • 流式Json上传,不需要额外的库;
    • 能处理环行和相对重定向;
    • 和你的app大小相比来说,库的size很小,所有的一切只有90kb;
    • 在各种各样的移动连接环境中具备自动智能请求重试机制;
    • 自动的gzip响应解码;
    • 内置多种形式的响应解析,有原生的字节流,string,json对象,甚至可以将 response写到文件中;
    • 永久的cookie保存,内部实现用的是Android的SharedPreferences;
    • 通过BaseJsonHttpResponseHandler和各种json库集成;
    • 支持SAX解析器;
    • 支持各种语言和content编码,不仅仅是UTF-8;

    Gradle 中引用

    在app的buid.gradle中添加
    compile 'com.loopj.android:android-async-http:1.4.9'

    使用

    官方建议是通过静态类的方法来使用
    twitter的例子
    <pre> import com.loopj.android.http.*;
    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; }}
    </pre>

    在client 端就可以这么用了

    import org.json.*;import com.loopj.android.http.*;class TwitterRestClientUsage {    
    public void getPublicTimeline() throws JSONException {        TwitterRestClient.get("statuses/public_timeline.json", null, new JsonHttpResponseHandler() {           
     @Override           
     public void onSuccess(int statusCode, Header[] headers, JSONObject response) {              
      // If the response is JSONObject instead of expected JSONArray            }                     
       @Override        
        public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {                
    // Pull out the first event on the public timeline              
          JSONObject firstEvent = timeline.get(0);           
           String tweetText = firstEvent.getString("text");          
          // Do something with the response                         
             System.out.println(tweetText);         
       }       
     });   
     }
    

    传参:

    RequestParams params = new RequestParams();
    params.put("key", "value");
    params.put("more", "data");
    

    相关文章

      网友评论

          本文标题:android-async-http库的使用

          本文链接:https://www.haomeiwen.com/subject/cyqrdttx.html