jjh*_*son 6 java api android asynchronous okhttp
我试图使用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();
}
Run Code Online (Sandbox Code Playgroud)
上面是我的代码,异常正在抛出
Response response = client.newCall(request).execute();
Run Code Online (Sandbox Code Playgroud)
我也读过Okhhtp支持异步请求,但我真的找不到一个干净的android解决方案,因为大多数似乎使用一个使用AsyncTask的新类<> ??
任何帮助或建议都非常感谢,谢谢...
Moh*_*uag 23
要发送异步请求,请使用以下命令:
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
}
});
}
Run Code Online (Sandbox Code Playgroud)
并这样称呼它:
case R.id.btLogin:
try {
doGetRequest("http://myurl/api/");
} catch (IOException e) {
e.printStackTrace();
}
break;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19205 次 |
| 最近记录: |