【问题标题】:Android HTTPUrlConnection POSTAndroid HTTPUrlConnection POST
【发布时间】:2012-05-25 18:41:45
【问题描述】:

我正在使用 HttpURLConnection 通过 POST 将数据发送到服务器。我设置了标头,然后获取输出流并写入 5 个字节的数据(“M=005”),然后关闭输出流。

在服务器上,我收到所有标题,内容长度正确,但随后我得到一个零长度行,服务器挂在 readLine 上。

似乎发生的是客户端关闭实际上从未发生过,因此不会写入整个数据,因此服务器永远不会得到它。

我已经阅读了许多示例并尝试了各种更改,看看我是否可以以任何方式实现这一点,但结果都不尽如人意。例如关闭保持活动,在我的数据结束时强制使用 CRLF(这会强制我的数据在服务器上输出,但连接仍然没有关闭。(这只是为了测试),尝试打印写入器。

由于许多示例都在做我正在做的事情,我认为这很简单,我忽略了它,但我只是看不到它。任何帮助将不胜感激。

    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. 

【问题讨论】:

    标签: android post httpurlconnection


    【解决方案1】:

    哎呀。我们服务器端的错误是执行 readLine 而不是字符读取。由于没有 CRLF,它会挂起。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-15
      相关资源
      最近更新 更多