gpt4 book ai didi

java - 同步请求失败 HTTP

转载 作者:行者123 更新时间:2023-12-01 09:35:30 25 4
gpt4 key购买 nike

我正在使用 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。

这个问题有解决办法吗

最佳答案

在后台线程中执行如下所示的进程:

OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(15, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();

new AsyncTask<Void, Void, JSONArray>() {

@Override
protected JSONArray doInBackground(Void... voids) {
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();

try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return new JSONArray(response.body().string());
} else {
// notify error
}
} catch (IOException e) {
// notify error e.getMessage()
}

return null;
}

@Override
protected void onPostExecute(JSONArray jsonArray) {
super.onPostExecute(jsonArray);
if (jsonArray != null && jsonArray.size() > 0) {
// notify status using LocalBroadcastManager or EventBus
}
}
}.execute();

关于java - 同步请求失败 HTTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38987358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com