2014-02-06 66 views
1

我需要schoolname=xyz&schoolid=1234到服务器。我写了下面Android客户端代码:当发送请求到服务器与HttpURLConnection时缺少参数

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参数丢失。我错过了什么或错了什么?

回答

1

我想通了,我自己的原因,是我忘了叫flush()输出流。刷新后,一切正常。

+0

你不仅应该flush(),还应该关闭()你的流。 – hgoebl

+0

当然,我已经关闭它,但没有在我的问题中提及它。但是,谢谢。 –

1

对于http post,您无法使用格式“key = value & key1 = value1”。这将工作得很好,只为得到。在这种情况下,你需要的是这样的:

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();