我需要发布 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
参数丢失。我错过了什么或做错了什么?
答案 0 :(得分:1)
看一下[这个解释How to use a HttpURLConnection to POST data
的例子如果您打算进行大量的网络沟通,请查看Square's Retrofit,这将有助于您自动完成大部分工作。
答案 1 :(得分:1)
对于http post,您不能使用格式“key = value& key1 = value1”。这只会对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();
答案 2 :(得分:1)
我想通了自己,原因是我忘了在输出流上调用flush()
。冲洗后,一切正常。