安卓HTTPUrlConnection POST

3
我正在使用HttpURLConnection通过POST发送数据到服务器。我设置了头信息,然后获取输出流并写入5个字节的数据(“M=005”),然后关闭输出流。
在服务器上,我接收到所有头信息和正确的内容长度,但是我会得到一个零长度的行,并且服务器会在readLine上挂起。
似乎客户端关闭从未真正发生,因此整个数据没有被写入,因此服务器永远无法获得它。
我已经阅读了许多示例,并尝试了各种更改,以查看是否可以以任何方式影响这一点,但都不尽人意。例如关闭保持活动状态、在我的数据末尾强制使用CRLF(这会将我的数据推出服务器,但连接仍然不会关闭。这只是用于测试)、尝试使用PrintWriter。
由于许多示例都在做我正在做的事情,所以我假设我忽略了一些简单的东西,但我就是看不到。任何帮助将不胜感激。
    StringBuilder postDataBuilder.append("M=").append(URLEncoder.encode("005", UTF8));
    byte[] postData = null;
    postData = postDataBuilder.toString().getBytes();


    url = new URL("http://" + serverAddress + ":" + String.valueOf(serverPort));
    conn = (HttpURLConnection) url.openConnection();

    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Length", Integer.toString(postData.length));
    conn.setUseCaches(false);

    OutputStream out = conn.getOutputStream();
    out.write(postData);
    out.close();

    int responseCode = conn.getResponseCode();

    // After executing the above line the server starts to successfully readLines
    // until it gets to the post data when the server hangs.  If I restart the
    // client side then the data finally gets through but the connection on the
    // server side never ends. 
1个回答

3

糟糕,我们服务器端出现了 bug,本应该使用字符读取,但实际上使用了 readLine。由于没有 CRLF(回车换行),程序会一直卡在这里。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接