【问题标题】:Synchronous request failing HTTP同步请求失败 HTTP
【发布时间】: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


【解决方案1】:

在后台线程中执行如下处理:

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();

【讨论】:

  • 无需使用Android笨拙的AsyncTask。 call.enqueue(Callback) 就是你想要的。
猜你喜欢
  • 1970-01-01
  • 2016-09-07
  • 2014-11-19
  • 1970-01-01
  • 2016-12-17
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 2015-04-10
相关资源
最近更新 更多