You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

OkHttp请求响应失败,返回okhttp3.internal.http.RealResponseBody@9fce4c6求助

OkHttp请求失败返回okhttp3.internal.http.RealResponseBody@xxx问题排查与解决

问题现象

使用OkHttp处理接口响应时,请求未成功,返回如下报错:

failed to respond due to okhttp3.internal.http.RealResponseBody@9fce4c6

对应的处理代码:

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
    if(response.isSuccessful()){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(response.body().string());
            JSONArray jsonArray = jsonObject.getJSONArray("choices");
            String result = jsonArray.getJSONObject(0).getString("text");
            addResponse(result.trim());

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }else{
        addResponse("Failed to response due to "+response.body().toString());
    }
}

问题原因

response.body().toString()并没有返回实际的错误响应内容,因为OkHttp的RealResponseBody类没有重写toString()方法,默认输出的是对象的内存地址(即okhttp3.internal.http.RealResponseBody@9fce4c6这种形式),无法获取到服务端返回的具体错误信息。

解决方案

要获取真实的错误响应内容,需要调用response.body().string()读取响应体,同时结合响应状态码、状态消息来完善错误提示,还要处理可能的异常和空指针情况。

修改后的代码示例:

@Override
public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
    if(response.isSuccessful()){
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(response.body().string());
            JSONArray jsonArray = jsonObject.getJSONArray("choices");
            String result = jsonArray.getJSONObject(0).getString("text");
            addResponse(result.trim());

        } catch (JSONException e) {
            e.printStackTrace();
            addResponse("解析响应失败:" + e.getMessage());
        }

    }else{
        String errorMsg;
        try {
            // 读取错误响应体内容,先判空避免空指针
            String errorBody = response.body() != null ? response.body().string() : "无错误内容";
            errorMsg = String.format("请求失败,状态码:%d,状态消息:%s,错误内容:%s",
                    response.code(), response.message(), errorBody);
        } catch (IOException e) {
            e.printStackTrace();
            errorMsg = String.format("请求失败,状态码:%d,状态消息:%s,读取错误内容失败",
                    response.code(), response.message());
        }
        addResponse(errorMsg);
    }
}

注意事项

  • 响应体的string()方法只能调用一次,调用后会消耗响应体的输入流,再次调用会抛出异常,若需要多次使用需先将内容保存到变量中。
  • 必须对response.body()进行判空处理,避免出现空指针异常。

内容的提问来源于stack exchange,提问作者Tsandesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 13:03:13