天天看點

Android網絡請求庫——android-async-http

在iOS開發中有大名鼎鼎的ASIHttpRequest庫,用來處理網絡請求操作,今天要介紹的是一個在Android上同樣強大的網絡請求庫android-async-http,目前非常火的應用Instagram和Pinterest的Android版就是用的這個網絡請求庫。這個網絡請求庫是基于Apache HttpClient庫之上的一個異步網絡請求處理庫,網絡處理均基于Android的非UI線程,通過回調方法處理請求結果。

其主要特征如下:

  • 處理異步Http請求,并通過匿名内部類處理回調結果
  • Http請求均位于非UI線程,不會阻塞UI操作
  • 通過線程池處理并發請求
  • 處理檔案上傳、下載下傳
  • 響應結果自動打包JSON格式
  • 自動處理連接配接斷開時請求重連

使用android-async-http也非常簡單,到官網​​http://loopj.com/android-async-http/​​下載下傳依賴jar包,導入工程中libs檔案夾下并添加到工程路徑即可。通過下面的代碼來建立一個異步請求:

AsyncHttpClient client = new AsyncHttpClient();
        client.get("http://www.baidu.com", new AsyncHttpResponseHandler() {
          
            @Override
            public void onSuccess(String response) {
                System.out.println(response);
                textView.setText(response);
            }
            
            @Override
            public void onStart() {
              super.onStart();
              System.out.println("onStart");
            }
            
            @Override
            public void onFinish() {
              super.onFinish();
              System.out.println("onFinish");
            }
            
        }      

通過Get請求指定的URL并通過回調函數處理請求結果,同時,請求方式還支援POST和PUT,請求的同時還支援參數傳遞,下面看看如何通過JSON字元串作為參數通路伺服器:

try {
          JSONObject jsonObject = new JSONObject();
          jsonObject.put("username", "ryantang");
          StringEntity stringEntity = new StringEntity(jsonObject.toString());
          client.post(MainActivity.this, "http://api.com/login", stringEntity, "application/json", new JsonHttpResponseHandler(){

            @Override
            public void onSuccess(JSONObject jsonObject) {
              super.onSuccess(jsonObject);
              
            }
            
          });
        } catch (JSONException e) {
          e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
        }      

官方推薦的使用方法,使用一個靜态的請求對象,我們來看看官方例舉的一個通路Twitter的API的例子:

import com.loopj.android.http.*;

public class TwitterRestClient {
  private static final String BASE_URL = "http://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;
  }
}      

使用方法:

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(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);
            }
        });
    }
}      

由于涉及網絡請求,最後别忘了添權重限:

<uses-permission android:name="android.permission.INTERNET" />      

其他功能例如上傳、下載下傳檔案等大家可以去

​​官網​​

檢視

post

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

AsyncHttpClient client = new AsyncHttpClient();
client.post("http://www.google.com", params, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(String response) {
        System.out.println(response);
    }
});