java.io.IOException : unexpected end of stream on Connection? 异常

标签 java android httpurlconnection okhttp

<分区>

调用我们的内部网络服务之一似乎出现以下错误:

java.io.IOException: unexpected end of stream on Connection{webservicessandbox.xxx.com:443, proxy=DIRECT@ hostAddress=174.143.185.13 cipherSuite=TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA protocol=http/1.1} (recycle count=0)

从我在其他地方看到的情况来看,这被认为是服务器问题,但是当在浏览器或 IOS 中调用 WS 时,我们没有看到这个问题。我同时使用了 OkHTTP 和手动 HTTPUrlConnection 实现,它似乎没有任何区别。有人有什么想法吗?

OKHttp:
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .addHeader("Authorization", "Bearer " + apiToken)
                    .addHeader("content-type", "application/json")
                    .url(uri)
                    .build();
HTTPURLConnection:
            URL myURL = new URL(uri);
            HttpsURLConnection myConnection = (HttpsURLConnection) myURL.openConnection();
            myConnection.setConnectTimeout(TIMEOUT_MILLISEC);
            myConnection.setDoOutput(false);
            myConnection.setRequestMethod("GET");
            myConnection.setRequestProperty("Authorization", "Bearer " + apiToken);
            myConnection.setRequestProperty("content-type", "application/json");
            int respCode = myConnection.getResponseCode();

最佳答案

请尝试以下可能的解决方案(在我看来):

1- 尝试使用 retryOnConnectionFailure(true) 如下:

OkHttpClient client = new OkHttpClient.Builder()
    .retryOnConnectionFailure(true)
    .build();

2- 尝试添加:request.addHeader("Connection","close")(大多数情况下这是解决方案,尊重 Kartik 的回答。)

Request request = new Request.Builder()
                    .addHeader("Authorization", "Bearer " + apiToken)
                    .addHeader("content-type", "application/json")
                    .addHeader("Connection","close")
                    .url(uri)
                    .build();

3-请增加服务器的响应时间(设置得尽可能高),然后重试。

另见:OkHTTP Websocket: Unexpected end of steam on Connection

关于java.io.IOException : unexpected end of stream on Connection? 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52726909/

相关文章:

java - Hibernate 不会在插入时将外键设置为父级主键的值

android - 使用 HttpUrlConnection 向服务器发送请求

Android 启动应用程序从具有多种服务的 BroadcastReceiver 启动

java - android中的客户端证书

json - 是否可以仅使用 JDK 或 HttpComponents 处理 JSON 响应?

Java 邮件显示身份验证失败

java - 房间@查询错误 : Cannot find method parameters

java - 如何在android中点击后永远隐藏按钮?

Android 加号 ("+") 在 url

android - 如何在 Android 中添加菜单而不会出现 "R"错误