发送 POST 请求并读取响应。 conn.getInputStream() 时出现 IOException

Send POST request and read response. IOException when conn.getInputStream()

我到处搜索都无法解决我的问题。我有 AsyncTask,在 doInBackground 我有:

 protected Void doInBackground(byte[]... params) {
 try {
    URL url = new URL(stringURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // Allow Inputs
    conn.setDoInput(true);
    // Allow Outputs
    conn.setDoOutput(true);
    // Don't use a cached copy.
    onn.setUseCaches(false);
    // Use a post method.
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "text/html; charset=UTF-8");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Accept", "text/html");
    conn.setRequestProperty("Content-Length", params[0].length);

    OutputStream out = conn.getOutputStream();
    out.write(params[0]);
    out.flush();
    out.close();

    InputStream is = conn.getInputStream();
    int ch;
    StringBuffer b =new StringBuffer();
    while( ( ch = is.read() ) != -1 ){
       b.append( (char)ch );
    }
    String s = b.toString();

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

我这样调用我的异步任务:new httpRequestResponseTask().execute(byteArray);

每次我都成功发送请求并且在我尝试读取响应后我得到 java.io.IOException: unexpected end of stream on Connection... 当我打电话给 conn.getInputStream() 时。我打电话时遇到同样的异常 conn.getResponseCode()conn.getResponseMessage().

我可以看到服务器收到我的请求并成功发送响应。但是我不明白。

我尝试了很多想法(其中一些很疯狂)只是为了测试:

*我在设置属性后放置 conn.connect(); - 相同的 IOexception

*不关闭 OutputStream - 相同的 IOexception

*添加像

这样的大超时
     conn.setReadTimeout(30000);
     conn.setConnectTimeout(35000);

响应应为 57 个字节,因此超时时间足够了。 没有变化。

*我尝试使用 url.OpenStream() 获取 InputStream。它只是挂起,什么也没发生。

*我尝试使用不同的属性,例如 Accept-Encoding 和更少的属性。

*我检查了url,里面没有space。 url 是这样的: http://example.com:8080.

我没有代理。我使用个人 phone 作为 Wi-Fi 热点,并用我的工作 phone 测试程序。它与 android 6.0 一起使用,但项目设置为 4.4 kitkat。

我应该以某种方式等待还是做其他事情?我没主意了...

更新异常堆栈

无内容长度

12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err: java.io.IOException: unexpected end of stream on Connection{example.com:8080, proxy=DIRECT@ hostAddress=*.*.*.* cipherSuite=none protocol=http/1.1} (recycle count=0)
12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:210)
12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:918)
12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:802)
12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:460)
12-21 14:38:09.516 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at com.xmltestservers.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:172)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at com.xmltestservers.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:125)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at android.os.AsyncTask.call(AsyncTask.java:295)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:234)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at java.lang.Thread.run(Thread.java:818)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err: Caused by: java.io.EOFException: \n not found: size=0 content=...
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
12-21 14:38:09.517 5481-5572/com.xmltestservers W/System.err:   ... 14 more

有内容长度

12-21 14:40:42.783 7729-7837/com.xmltestservers W/System.err: java.io.IOException: unexpected end of stream on Connection{example.com:8080, proxy=DIRECT@ hostAddress=*.*.*.* cipherSuite=none protocol=http/1.1} (recycle count=0)
12-21 14:40:42.784 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:210)
12-21 14:40:42.785 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpTransport.readResponseHeaders(HttpTransport.java:80)
12-21 14:40:42.785 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:918)
12-21 14:40:42.785 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:802)
12-21 14:40:42.786 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:460)
12-21 14:40:42.786 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:405)
12-21 14:40:42.786 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:231)
12-21 14:40:42.786 7729-7837/com.xmltestservers W/System.err:     at com.xmltestservers.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:169)
12-21 14:40:42.786 7729-7837/com.xmltestservers W/System.err:     at com.xmltestservers.MainActivity$RetrieveFeedTask.doInBackground(MainActivity.java:125)
12-21 14:40:42.787 7729-7837/com.xmltestservers W/System.err:     at android.os.AsyncTask.call(AsyncTask.java:295)
12-21 14:40:42.787 7729-7837/com.xmltestservers W/System.err:     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-21 14:40:42.787 7729-7837/com.xmltestservers W/System.err:     at android.os.AsyncTask$SerialExecutor.run(AsyncTask.java:234)
12-21 14:40:42.787 7729-7837/com.xmltestservers W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
12-21 14:40:42.788 7729-7837/com.xmltestservers W/System.err:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
12-21 14:40:42.788 7729-7837/com.xmltestservers W/System.err:     at java.lang.Thread.run(Thread.java:818)
12-21 14:40:42.788 7729-7837/com.xmltestservers W/System.err: Caused by: java.io.EOFException: \n not found: size=57 content=f1f1f1340079c1eed5d9043324501c4ae6700647e093ea8a18b2e42c9d2acbd8...
12-21 14:40:42.789 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:200)
12-21 14:40:42.790 7729-7837/com.xmltestservers W/System.err:     at com.android.okhttp.internal.http.HttpConnection.readResponse(HttpConnection.java:191)
12-21 14:40:42.790 7729-7837/com.xmltestservers W/System.err:   ... 14 more

尝试使用此代码读取响应

BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

事实证明,响应没有任何 headers,我认为这就是问题所在。我用 HTTPClient 尝试过但没有用,因为响应中没有 headers (我认为异常不是有效的 HTTP 响应)。之后我尝试使用 Socket 并且它起作用了。这是代码:

Socket socket = new Socket(url.getHost(), url.getPort());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.write(hardcodedRequest);
out.flush();

InputStream inStream = socket.getInputStream();

byte[] resp = new byte[hardcodedResponse.length];
int res = inStream.read(resp);

//Check if the response is the correct one.
if (!Arrays.equals(resp, hardcodedResponse) && res != hardcodedResponse.length) {

}
out.close();

我知道响应支持是什么,所以我对其进行了硬编码并将其与服务器的响应进行比较。