Json 使用 OkHttp 时收到问题

Json receiving issue while using OkHttp

我正在使用 OkHttp 从 api 的 json 数据中检索数据。我写了下面的代码:

OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(forecastUrl).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                // TODO: manage failure
                // try again
                doInBackground(params);
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String jsonData = response.body().string();
                    nowDataList.clear();
                    hourlyDataList.clear();
                    dailyDataList.clear();
                    try {
                        nowDataList.add(getNowData(jsonData));
                        for (int i = 0; i < 24; i++) {
                            hourlyDataList.add(getHourlyData(jsonData, i));
                        }
                        for (int i = 0; i < 8; i++) {
                            dailyDataList.add(getDailyData(jsonData, i));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    // if response is not successful try again
                    doInBackground(params);
                }
            }

现在上面的代码以良好的互联网速度接收完整数据 (WiFi/LTE)。 但是,我有时无法获得完整的 json 网速较慢的数据(主要是在 2G/3G 上)

我也尝试了以下解决方案:Android JSON receive issue。虽然不是基于OkHttp,但是我自己修改了代码,但是没有盈利。

请帮我解决问题并提前致谢。

对于慢速连接尝试更改默认超时:

client.setConnectTimeout(15, TimeUnit.SECONDS);
client.setReadTimeout(15, TimeUnit.SECONDS);

onResponse 不会等待获得整个响应,如果您的响应很大/或者您的互联网连接不佳,那么这可能是个问题。

我用过这个,它对我有用。

// get the full response
response = client.newCall(request).execute();

然后继续你的代码。希望对你有帮助。