【问题标题】:Android POST Message Doesn't get SentAndroid POST 消息未发送
【发布时间】:2011-06-21 11:51:13
【问题描述】:

我遇到了一个相当奇怪的错误。我编写了一个将简单文本文件上传到服务器的 android 应用程序。连接代码如下:

try {
    URL = new URL(myURL);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="+"---");
    DataOutputStream output = new DataOutPutstream(connection.getOutputStream());
    output.writeBytes(<my post request>);
    output.flush();
    output.close();
    connection.connect();
}

当我运行此方法时,发布请求永远不会发送到服务器。什么都没有显示在wireshark上,如果我查看logcat,没有错误并且连接正常,POST消息永远不会发送。但是,如果我在 connection.connect() 之后添加一个简单的行,例如:

connection.getResponseCode();

突然 POST 消息发送过来没有问题。这里发生了什么?我是否需要获取响应代码才能发送消息?

【问题讨论】:

    标签: android html post


    【解决方案1】:
    1. Why do you have to call URLConnection#getInputStream to be able to write out to URLConnection#getOutputStream? 简而言之,您必须调用 getInputStream() 并关闭它。 getResponseCode() 也可以工作,因为它需要已建立的连接。
    2. 你不需要打电话

      connection.connect(); 这是多余的。

    您可以从这里获得工作样本:http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139

    【讨论】:

      【解决方案2】:

      您将 doInput 设置为 true。因此,可能 url 连接等待输入。尝试将其设置为 false。但我也可能是错的。这只是一个猜测。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-21
        • 2012-05-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多