真的遇到这个问题。 下面的代码假设将POST值(用户名,密码)发送到服务器,服务器应该只使用GET和POST的var_dump进行响应。
PHP代码:
var_dump($_POST);
var_dump($_GET);
ANDROID CODE:
InputStream is = null;
//http post
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url + "?test=test");
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Accept", "application/json");
// place them in an array list
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", "1123"));
nameValuePairs.add(new BasicNameValuePair("password", "123123"));
// add array list to http post
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i("Network", "POST URL: " + url);
Log.i("Network", "POST ARGS: " + jsonObj.toString());
} catch(Exception e){
Log.e("Network", "POST Error in http connection " + e.toString());
}
但我得到的是:
array(0) {
}
array(1) {
["test"]=> string(4) "test"
}
我用curl测试了服务器:curl -F'username = test'http://xx.xx.xx.xx/test.php 它给了我正确的回报:
array(1) {
["username"]=> string(9) "test"
}
array(0) {
}
那么我在android帖子中做错了什么?
答案 0 :(得分:1)
您不应将Content-Type
标题设置为application/json
。您可以不设置Content-Type
标头,也可以手动将其设置为application/x-www-form-urlencoded
。