2016-01-23 39 views
6

我正在嘗試使用Okhttp庫通過API將我的android應用程序連接到我的服務器。Android Okhttp異步調用

我的api調用發生在按鈕單擊上,我收到以下內容android.os.NetworkOnMainThreadException。我知道這是因爲我正在嘗試主線程上的網絡調用,但我也努力在Android上找到一個乾淨的解決方案,以便如何使這個代碼使用另一個線程(異步調用)。

@Override 
public void onClick(View v) { 
    switch (v.getId()){ 
     //if login button is clicked 
     case R.id.btLogin: 
      try { 
       String getResponse = doGetRequest("http://myurl/api/"); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      break; 
    } 
} 

String doGetRequest(String url) throws IOException{ 
    Request request = new Request.Builder() 
      .url(url) 
      .build(); 

    Response response = client.newCall(request).execute(); 
    return response.body().string(); 

} 

以上是我的代碼,異常被上線

Response response = client.newCall(request).execute(); 

香港專業教育學院還讀了Okhhtp支持異步請求,但我真的無法找到Android的一個乾淨的解決方案,因爲大多數拋出似乎使用一個新類,使用AsyncTask <> ??

任何幫助或建議,我們非常感激,三江源...

回答

16

要發送異步請求,使用此:

void doGetRequest(String url) throws IOException{ 
    Request request = new Request.Builder() 
      .url(url) 
      .build(); 

    client.newCall(request) 
      .enqueue(new Callback() { 
       @Override 
       public void onFailure(final Call call, IOException e) { 
        // Error 

        runOnUiThread(new Runnable() { 
         @Override 
         public void run() { 
          // For the example, you can show an error dialog or a toast 
          // on the main UI thread 
         } 
        }); 
       } 

       @Override 
       public void onResponse(Call call, final Response response) throws IOException { 
        String res = response.body().string(); 

        // Do something with the response 
       } 
      }); 
} 

&這樣調用它:

case R.id.btLogin: 
    try { 
     doGetRequest("http://myurl/api/"); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    break; 
+0

有不需要'try {...} catch(IOException e){...}'當然'doGetRequest(String url)拋出IOException {' –

+0

@ V.Kalyuzhnyu Try .. catch將處理拋出的錯誤b Ÿ'doGetRequest'的'IOException' – kirtan403

+0

謝謝。你是對的 –