【发布时间】:2016-08-17 02:52:59
【问题描述】:
我正在使用 okHTTP 库发出 http 请求。它通过了,但有时,我在 android 中的工作在没有完全响应的情况下进行。我意识到这是因为我的请求的性质是异步的。
OkHttpClient client = new OkHttpClient();
String url = "https://beta-pp-api.polkadoc.com/v1.0/products?category=CP&available_via=mail_order";
{
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", authentication.getToken())
.addHeader("Content-Type", "application/json")
.addHeader("Accept", "application/json")
.addHeader("X-Service-Code", "PP")
.get()
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e){
//do nothing!
}
@Override
public void onResponse(Response response) throws IOException
try {
jsonArray = new JSONArray(response.body().string());
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
我试过打电话
Response response = client.newCall(request).execute();
但是,它失败了,因为在 Android 中我们无法在主线程上调用同步请求。导致错误 NetworkOnMainThread android.os。
有没有办法解决这个问题。
【问题讨论】:
-
然后,在新线程上执行调用。
标签: java android rest android-studio okhttp