同步请求失败的HTTP

时间:2016-08-17 02:52:59

标签: java android rest android-studio okhttp

我正在使用okHTTP库发出http请求。它通过但有时,我在android的工作进展没有完全响应到来。我意识到这种情况正在发生,因为我的请求是ASYNC。

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中我们无法在主线程上调用Sync请求。导致错误NetworkOnMainThread android.os。

是否有解决此问题的方法。

1 个答案:

答案 0 :(得分: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();