【问题标题】:missing parameter when sending request to server with HttpURLConnection使用 HttpURLConnection 向服务器发送请求时缺少参数
【发布时间】:2014-02-06 16:50:48
【问题描述】:

我需要发布 schoolname=xyz&schoolid=1234 到服务器。我编写了以下Android客户端代码:

String data = "schoolname=xyz&schoolid=1234";

//The url is correct
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Accept-Encoding", "gzip");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(data.toString().getBytes("UTF-8"));

//response complains that missing parameter 'schoolname'
int responseCode = conn.getResponseCode();
...

在我使用上述代码发送请求后,服务器却不断抱怨缺少schoolname 参数。我错过了什么或做错了什么?

【问题讨论】:

    标签: android httpurlconnection android-networking


    【解决方案1】:

    看看[这个解释How to use a HttpURLConnection to POST data的例子

    如果您计划进行大量网络通信,请查看Square's Retrofit,它将帮助您自动完成大部分工作。

    【讨论】:

      【解决方案2】:

      您不能将“key=value&key1=value1”的格式用于 http post。这只适用于get。在这种情况下,您需要这样的东西:

      List<NameValuePair> nameValuePairs;
      nameValuePairs.add(new BasicNameValuePair("schoolname", "xyz"));
      nameValuePairs.add(new BasicNameValuePair("schoolid", "1234"));
      HttpPost httpPost = new HttpPost(url);
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
      httpPost.execute();
      

      【讨论】:

        【解决方案3】:

        我自己想通了,原因是我忘记在输出流上调用flush()。刷完之后,一切正常。

        【讨论】:

        • 你不仅应该flush(),还应该close()你的信息流。
        • 当然,我已经关闭了它,只是在我的问题中没有提到它。不过谢谢。
        猜你喜欢
        • 1970-01-01
        • 2016-10-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-24
        • 1970-01-01
        • 2012-01-03
        相关资源
        最近更新 更多