2016-01-23 34 views
6

Okhttpライブラリを使用して、アンドロイドアプリをAPI経由でサーバーに接続しようとしています。Android Okhttp非同期呼び出し

ボタンクリックでAPI呼び出しが発生し、次のメッセージが表示されます。android.os.NetworkOnMainThreadException。私はこれがメインスレッドでネットワークコールを試みているという事実に気付いていますが、このコードで別のスレッド(非同期呼び出し)を使用する方法については、アンドロイドのクリーンなソリューションを見つけるのにも苦労しています。上記

@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が非同期リクエストをサポートしていますが、私は本当にほとんどのようアンドロイドのためのクリーンな解決策を見つけることができないことを読んで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

ありもちろんdoGetRequest(String url)はIOExceptionをスローする{' –

+0

@ V.Kalyuzhnyu try .. catchはエラーを投げたbを処理しますy 'doGetRequest'の' IOException' – kirtan403

+0

ありがとうございます。あなたは正しいです –

関連する問題