Jenkins流水线中OkHttp3报unexpected end of stream错误求助
Jenkins流水线中OkHttp3调用Docker容器服务报unexpected end of stream错误
在Jenkins流水线执行集成测试时,使用OkHttp3调用通过docker-compose.yml启动的容器服务(地址http://localhost:6000),抛出如下异常。本地运行无此问题,仅Jenkins环境出现该异常,尝试过其他帖子的解决方案但无效。
错误信息
java.io.IOException: unexpected end of stream on http://localhost:6000/... at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
客户端构建代码
List<Protocol> protocols = new ArrayList<Protocol>(); protocols.add(Protocol.HTTP_1_1); client = new OkHttpClient.Builder() .protocols(protocols) .readTimeout(120, TimeUnit.SECONDS) .connectTimeout(120, TimeUnit.SECONDS) .writeTimeout(120, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .build();
请求构建代码
String baseUrl = "http://localhost:6000/sender"; Request request = new Request.Builder() .url(baseUrl) .headers(headers) .header("accept", "application/json") .header("Connection", "close") .header("Cache-Control", "no-cache") .header("Content-Type", "application/json") .post(RequestBody.create(MediaType.parse("application/json"), payLoad)) .build(); Call call = client.newCall(request); return call.execute();
OkHttp3版本:3.14.9
排查方向与解决方案
- 修正服务地址的网络指向
如果Jenkins运行在容器中,localhost指向的是Jenkins容器自身而非宿主机。需将请求地址改为宿主机IP,或者把Jenkins容器和服务容器加入同一个Docker网络,使用容器名称作为地址(例如http://service-container-name:6000/sender)。 - 验证服务容器在Jenkins环境的可用性
在Jenkins流水线中添加步骤,执行docker ps确认服务容器正常运行,用curl命令测试服务地址是否可访问,排除服务未启动、端口映射失败的问题。 - 调整OkHttp连接配置
移除自定义的Connection: close请求头,让OkHttp自动管理连接;添加OkHttp日志拦截器,打印完整的请求和响应细节,定位是请求发送失败还是响应被截断:HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); client = new OkHttpClient.Builder() .protocols(protocols) .readTimeout(120, TimeUnit.SECONDS) .connectTimeout(120, TimeUnit.SECONDS) .writeTimeout(120, TimeUnit.SECONDS) .retryOnConnectionFailure(true) .addInterceptor(logging) .build(); - 检查Jenkins环境的网络限制
确认Jenkins部署环境没有防火墙、代理或网络策略阻止容器间/容器到宿主机的通信,确保6000端口可正常访问。
内容的提问来源于stack exchange,提问作者devumesh
相关产品推荐
相关产品推荐

