2016-01-23 38 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

谢谢。你是对的 –