I am attempting to use the Okhttp library to connect my android app to my server via API.
My api call is happening on a button click and I am receiving the following android.os.NetworkOnMainThreadException. I understand that this is due the fact I am attempting network calls on the main thread but I am also struggling to find a clean solution on android as to how make this code use another thread (async calls).
@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();
}
Above is my code, and the exception is being thrown on the line
Response response = client.newCall(request).execute();
Ive also read that Okhhtp supports Async requests but I really can't find a clean solution for android as most seem to use a new class that uses AsyncTask<>??
Any help or suggestions are much appreciated, thankyou...
To send an asynchronous request, use this:
& call it this way: