okhttp3.internal.http.RealResponseBody

本文解决了使用OkHttp进行网络请求时出现的数据解析错误问题。通过更改数据读取方式,从使用response.body().toString()更改为response.body().string(),成功避免了因数据类型不匹配导致的解析失败。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转载请注明链接:https://blog.csdn.net/feather_wch/article/details/81407581

解决OkHttp的报错问题:okhttp3.internal.http.RealResponseBody

如果有帮助请点个赞!万分感谢!

okhttp3.internal.http.RealResponseBody

报错提示

D/OkHttp: okhttp3.internal.http.RealResponseBody @ f11e81d

原因分析

通过OkHttp请求网络,结果请求下来的数据一直无法解析并且报错,这需要将String res = response.body().toString()更改为String res = response.body().string()

解决办法

旧代码:

@Override
public void onResponse(Call call, Response response) throws IOException {
    String str = response.body().toString();
    Log.d("OkHttp", str);
}

更改为:

@Override
public void onResponse(Call call, Response response) throws IOException {
    String str = response.body().string();
    Log.d("OkHttp", str);
}
java接入智谱清言Exception in thread "main" java.lang.RuntimeException: java.net.SocketTimeoutException: timeout at io.reactivex.internal.util.ExceptionHelper.wrapOrThrow(ExceptionHelper.java:45) at io.reactivex.internal.observers.BlockingMultiObserver.blockingGet(BlockingMultiObserver.java:90) at io.reactivex.Single.blockingGet(Single.java:2002) at com.zhipu.oapi.AbstractClientBaseService.execute(ClientV4.java:82) at com.zhipu.oapi.ClientV4.executeRequest(ClientV4.java:505) at com.zhipu.oapi.ClientV4.invoke(ClientV4.java:176) at com.zhipu.oapi.ClientV4.invokeModelApi(ClientV4.java:151) at com.jason.health.controller.AITest.Test1(AITest.java:70) at com.jason.health.controller.AITest.main(AITest.java:24) Caused by: java.net.SocketTimeoutException: timeout at okhttp3.internal.http2.Http2Stream$StreamTimeout.newTimeoutException(Http2Stream.kt:675) at okhttp3.internal.http2.Http2Stream$StreamTimeout.exitAndThrowIfTimedOut(Http2Stream.kt:684) at okhttp3.internal.http2.Http2Stream.takeHeaders(Http2Stream.kt:143) at okhttp3.internal.http2.Http2ExchangeCodec.readResponseHeaders(Http2ExchangeCodec.kt:96) at okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106) at okhttp3.internal.http.CallServerInterceptor.intercept(CallServerInterceptor.kt:79) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:34) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:95) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83) at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:109) at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76) at okhttp3.internal.http.RealInterce
03-18
### 问题分析 `java.net.SocketTimeoutException: connect timed out` 是 Java 中常见的网络异常之一,表示客户端在尝试与服务器建立连接时超过了设定的超时时间[^1]。这种问题可能由多种因素引起,例如网络延迟、目标服务器不可达、防火墙阻止请求或者未合理设置超时参数。 当调用智谱清言 API 出现 `SocketTimeoutException` 时,可以考虑以下几个方面来解决问题: --- ### 解决方案 #### 1. 设置合理的超时时间 在网络通信中,适当增加超时时间是一种常见做法。可以通过配置 HTTP 请求库中的 `connectTimeout` 和 `readTimeout` 参数实现这一点。以下是基于 OkHttp 的代码示例: ```java import okhttp3.OkHttpClient; import okhttp3.Request; public class ApiClient { public static void main(String[] args) throws Exception { OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(30, java.util.concurrent.TimeUnit.SECONDS) // 连接超时时间为30秒 .readTimeout(30, java.util.concurrent.TimeUnit.SECONDS) // 响应读取超时时间为30秒 .build(); Request request = new Request.Builder() .url("https://api.zhipu.com/some-endpoint") // 替换为目标API地址 .get() .build(); try (okhttp3.Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); } } } ``` 上述代码通过 OkHttp 库设置了更长的连接和读取超时时间,从而减少因短暂网络波动引发的超时风险[^3]。 --- #### 2. 使用重试机制 即使增加了超时时间,仍然可能出现偶发性的连接失败情况。此时可以在代码中引入重试逻辑,确保请求能够多次尝试直到成功为止。以下是一个简单的重试实现: ```java int maxRetries = 3; // 最大重试次数 for (int attempt = 1; attempt <= maxRetries; attempt++) { try { OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.zhipu.com/some-endpoint") .get() .build(); okhttp3.Response response = client.newCall(request).execute(); if (response.isSuccessful()) { System.out.println("Response received on attempt " + attempt); break; // 成功则退出循环 } else { Thread.sleep(2000); // 失败后等待2秒再重试 } } catch (Exception e) { if (attempt == maxRetries) { throw e; // 达到最大重试次数仍失败,则抛出异常 } Thread.sleep(2000); // 等待一段时间后再重试 } } ``` 此方法能够在一定程度上提高系统的鲁棒性,尤其是在不稳定网络环境下[^2]。 --- #### 3. 检查网络环境 除了调整代码外,还需要确认运行环境中是否存在潜在问题: - **本地网络状况**:测试当前设备与其他外部服务的连通性和延时。 - **目标服务器状态**:访问智谱清言官方文档或联系技术支持团队了解其服务健康状况。 - **代理/防火墙干扰**:某些企业内部网络可能会拦截对外请求,建议排查是否有类似的限制存在。 --- #### 4. 日志记录与监控 为了更好地定位问题根源,在实际生产环境中应当加入详细的日志记录功能。例如利用 SLF4J 或 Logback 工具捕获每次请求的关键信息(如耗时时长、返回码等),以便后续分析优化。 --- ### 总结 针对 `java.net.SocketTimeoutException` 异常,可以从多个角度入手解决,包括但不限于延长超时时间、实施自动重试策略以及改善基础架构条件。具体实施方案需结合项目需求权衡利弊而定。 ---
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猎羽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值