2016-01-23 22 views
6

Sto tentando di utilizzare la libreria Okhttp per collegare la mia app Android al mio server tramite API.Chiamate asincrone Android Okhttp

La mia chiamata API sta accadendo con un clic del pulsante e sto ricevendo il seguente android.os.NetworkOnMainThreadException. Capisco che questo è dovuto al fatto che sto tentando di effettuare chiamate di rete sul thread principale, ma sto anche cercando di trovare una soluzione pulita su Android per far sì che questo codice usi un altro thread (chiamate asincrone).

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

} 

In alto è il mio codice, e l'eccezione viene gettata sulla linea

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

Ive anche letto che Okhhtp supporta le richieste asincrone ma davvero non riesce a trovare una soluzione pulita per Android come la maggior parte sembra utilizzare una nuova classe che utilizza AsyncTask <> ??

Qualsiasi aiuto o suggerimenti sono molto apprezzati, thankyou ...

risposta

16

Per inviare una richiesta asincrona, utilizzare questo:

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

& chiamano in questo modo:

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

C'è non c'è bisogno di 'try {...} catch (IOException e) {...}' e ovviamente 'doGetRequest (String url) genera IOException {' –

+0

@ V.Kalyuzhnyu Try .. catch gestirà l'errore gettato b y 'DoGetRequest''s' IOException' – kirtan403

+0

Grazie. Hai ragione: –