詳解Android的OkHttp包編寫非同步HTTP請求調用的方法_Android

來源:互聯網
上載者:User

OkHttp 除了支援常用的同步 HTTP 要求之外,還支援非同步 HTTP 要求調用。在使用同步調用時,當前線程會被阻塞,直到 HTTP 要求完成。當同時發出多個 HTTP 要求時,同步調用的效能會比較差。這個時候通過非同步呼叫可以提高整體的效能。
在通過 newCall 方法建立一個新的 Call 對象之後,不是通過 execute 方法來同步執行,而是通過 enqueue 方法來添加到執行隊列中。在調用 enqueue 方法時需要提供一個 Callback 介面的實現。在 Callback 介面實現中,通過 onResponse 和 onFailure 方法來處理響應和進行錯誤處理。
非同步呼叫的樣本

public class AsyncGet {  public static void main(String[] args) throws IOException {  OkHttpClient client = new OkHttpClient();  Request request = new Request.Builder()      .url("http://www.baidu.com")      .build();  client.newCall(request).enqueue(new Callback() {    public void onFailure(Request request, IOException e) {      e.printStackTrace();    }    public void onResponse(Response response) throws IOException {      if (!response.isSuccessful()) {        throw new IOException("伺服器端錯誤: " + response);      }      System.out.println(response.body().string());    }});  }}

覺得okHttp最難寫的地方應該就是Callback了。
相信很多人都會遇到,如果Callback回來之後,我的Activity finish了,或是我的Fragment replace了。
此時更改UI,就會產生找不到View的問題。
而且Callback回來,居然是在backgroundThread上,
這時候如果要操作View又要切換到mainThread去,略顯麻煩。
所以我在寫的時候,是沒有使用Callback的 以下提供一種漂亮(自認...)的寫法給大家做參考。

/* 以fragment為例 */public class BaseFragment extends Fragment implements Handler.Callback {private static final int MSG_QUERY_DATA = 0x00;private static final int MSG_DISPLAY_DATA = 0x01;@Overridepublic void onAttach(Activity activity) {  super.onAttach(activity);  this.activity = activity;  /* setup handler */  HandlerThread handlerThread = new HandlerThread(getClass().getName());  handlerThread.start();  backgroundHandler = new Handler(handlerThread.getLooper(), this);  uiHandler = new Handler(activity.getMainLooper(), this);}@Overridepublic void onViewCreated(View view, @Nullable Bundle savedInstanceState) {  /* start */  backgroundHandler.sendEmptyMessage(MSG_QUERY_DATA);}@Overridepublic void onDestroyView() {  /* 將Message清空,backgroundThread結束掉 */  backgroundHandler.removeCallbacksAndMessages(null);  uiHandler.removeCallbacksAndMessages(null);  backgroundHandler.getLooper().quit();  super.onDestroyView();}@Overridepublic boolean handleMessage(Message msg) {  /* 如果fragment不在Activity上了,直接return掉,避免NPE */  if (!isAdded()) return false;  /* 做各種MSG */  switch(msg.what){    case MSG_QUERY_DATA:      // do okHttp without callback      Response response = client.newCall(request).execute();      // 傳回 uiThread 做UI更新      Message respMsg = uiHandler.obtainMessage();      respMsg.what = MSG_DISPLAY_DATA;      respMsg.obj = response;      backgroundHandler.sendMessage(respMsg);      break;    case MSG_DISPLAY_DATA:      Response apiResponse = (Response)msg.obj;      // 失敗      if(null == apiResponse){        //show error      }      // 成功      else{        //display data on UI      }      break;    return false;  }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.