Java Android Okhttp异步调用
我正在尝试使用Okhttp库通过API将我的android应用程序连接到我的服务器 我的API调用在点击按钮时发生,我收到以下android.os.NetworkOnMainThreadException。我知道这是因为我尝试在主线程上进行网络调用,但我也在努力在Android上找到一个干净的解决方案,如何让代码使用另一个线程(异步调用) 上面是我的代码,异常被抛出Java Android Okhttp异步调用,java,android,api,asynchronous,okhttp,Java,Android,Api,Asynchronous,Okhttp,我正在尝试使用Okhttp库通过API将我的android应用程序连接到我的服务器 我的API调用在点击按钮时发生,我收到以下android.os.NetworkOnMainThreadException。我知道这是因为我尝试在主线程上进行网络调用,但我也在努力在Android上找到一个干净的解决方案,如何让代码使用另一个线程(异步调用) 上面是我的代码,异常被抛出 Response response = client.newCall(request).execute(); 我还读到Okhht
Response response = client.newCall(request).execute();
我还读到Okhhtp支持异步请求,但我确实找不到一个适用于Android的干净解决方案,因为大多数人似乎使用了一个新类,该类使用了异步任务?要发送异步请求,请使用以下方法:
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;
在
try{…}catch(IOException e){…}
中没有必要,当然doGetRequest(stringurl)抛出IOException{
@V.Kalyuzhnyu try..catch将处理doGetRequest
的IOException
字符串res=response.body().String()抛出的错误;
将在响应主体较大且不立即可用时进行阻止(因此可能需要在单独的线程池中进行阻止操作)。此外–最好将其包装在try(response res=response)
中,以确保响应是关闭的,如果响应中没有主体。
case R.id.btLogin:
try {
doGetRequest("http://myurl/api/");
} catch (IOException e) {
e.printStackTrace();
}
break;