Android Okhttp异步调用
Android Okhttp asynchronous calls
我正在尝试使用 Okhttp 库通过 API 将我的 android 应用程序连接到我的服务器。
我的 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 的干净解决方案,因为大多数人似乎使用新的 class,它使用 异步任务<>?
要发送异步请求,请使用:
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;
我正在尝试使用 Okhttp 库通过 API 将我的 android 应用程序连接到我的服务器。
我的 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 的干净解决方案,因为大多数人似乎使用新的 class,它使用 异步任务<>?
要发送异步请求,请使用:
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;