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
相关产品推荐
相关产品推荐

