致命异常:OkHttp分派器

fis*_*hau 3 java android okhttp

我在Android应用中使用OkHttp库向天气API发出Web请求。我已经实现了我的代码,并且在执行请求时遇到了致命错误。

我已经在清单中添加了INTERNET权限。

MainActivity.java:

private CurrentWeather currentWeather;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        final ActivityMainBinding binding = DataBindingUtil.setContentView(MainActivity.this, R.layout.activity_main);

        String apiKey = "xxx";
        double latitude = 37.8267;
        double longitude = -122.4233;
        String forecastURL = String.format("https://api.darksky.net/forecast/%s/%f,%f", apiKey, latitude, longitude);

        if (isNetworkAvailable()) {
            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(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    try {
                        Log.v(TAG, response.body().string());
                        String jsonData = response.body().string();
                        if (response.isSuccessful()) {
                            currentWeather = getCurrentDetails(jsonData);
                        }

                    } catch (IOException e) {
                        Log.e(TAG, e.getLocalizedMessage());
                    } catch (JSONException e) {
                        Log.e(TAG, e.getLocalizedMessage());
                    }
                }
            });
        }
        Log.d(TAG, "Main UI code is running");
    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {

        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");

        JSONObject currently = forecast.getJSONObject("currently");

        String icon = currently.getString("icon");
        String locationLabel = "Alcatraz Island";
        String summary = currently.getString("summary");
        long time = currently.getLong("time");
        double humidity = currently.getDouble("humidity");
        double precipProbability = currently.getDouble("precipProbability");
        double temperature = currently.getDouble("temperature");

        return new CurrentWeather(locationLabel, icon, time, temperature, humidity, precipProbability, summary, timezone);
    }
Run Code Online (Sandbox Code Playgroud)

摇篮:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.squareup.okhttp3:okhttp:3.12.0'

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Run Code Online (Sandbox Code Playgroud)

然后,这是我遇到的异常:

2018-12-04 20:55:49.969 3314-3330/com.test.starmie E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: com.test.starmie, PID: 3314
    java.lang.IllegalStateException: closed
        at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:407)
        at okio.RealBufferedSource.rangeEquals(RealBufferedSource.java:401)
        at okhttp3.internal.Util.bomAwareCharset(Util.java:471)
        at okhttp3.ResponseBody.string(ResponseBody.java:175)
        at com.test.starmie.MainActivity$1.onResponse(MainActivity.java:66)
        at okhttp3.RealCall$AsyncCall.execute(RealCall.java:206)
        at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
        at java.lang.Thread.run(Thread.java:761)
Run Code Online (Sandbox Code Playgroud)

我目前不知道该怎么办。我已阅读了一遍,发现了一些有关该主题的帖子。根据我的收集,必须在runOnUiThread()块中进行UI更改。但是我没有在代码中进行任何UI更改,但仍然出现异常。

我还已经尝试将JSON解析代码放入runOnUiThread()中,并获得相同的致命异常结果。任何人有任何想法吗?

Sta*_*dar 13

Response身体只能食用一次。你两次

Log.v(TAG, response.body().string());
String jsonData = response.body().string();
Run Code Online (Sandbox Code Playgroud)

文档中的更多信息


Dej*_*sov 11

我遇到了同样的问题,并通过切换到 Java 8 兼容性解决了这个问题。在build.gradle文件下添加compileOptions

android {

    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}
Run Code Online (Sandbox Code Playgroud)


li2*_*li2 9

我尝试了所有答案,甚至将 okhttp 从 3.14.9 迁移到 4.4.0,但没有一个适合我的情况:我有一个继承自 的响应拦截器Interceptor

class ResponseInterceptor : Interceptor {
    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        if (!isSuccessful(response.code)) {
            handleErrorResponse(response)
        }
        return response
    }

    private fun handleErrorResponse(response: Response) {
        throw ApiException(response.body?.string()) // only called one time!
    }
}
Run Code Online (Sandbox Code Playgroud)

我终于通过改变修复了它

data class ApiException(val errorMessage: String?) : Exception(errorMessage)
// `Exception` is `typealias Exception = java.lang.Exception`
Run Code Online (Sandbox Code Playgroud)

import java.io.IOException
data class ApiException(val errorMessage: String?) : IOException(errorMessage)
Run Code Online (Sandbox Code Playgroud)

真的不知道为什么java.lang.Exception会引起这样的问题。


Hou*_*lla 8

这是由于使用了不同版本的 OkHttp 造成的。确保 com.squareup.okhttp3 中的所有依赖项都使用相同的版本。

例子:

implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
implementation 'com.squareup.okhttp3:okhttp:3.8.0'
Run Code Online (Sandbox Code Playgroud)


小智 5

就我而言,我已经打过response.body.string()一次电话但仍然崩溃了。把它修好了

ResponseBody responseBodyCopy = response.peekBody(Long.MAX_VALUE);
responseBodyCopy.string();
Run Code Online (Sandbox Code Playgroud)

来自github上的评论: https://github.com/square/okhttp/issues/1240#issuecomment-330813274