1

这个问题确实有问题。下面的代码假设将 POST 值(用户名、密码)发送到服务器,服务器应该只响应 GET 和 POST 的 var_dump。

PHP代码:

var_dump($_POST);
var_dump($_GET);

安卓代码:

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帖子中做错了什么?

4

1 回答 1

1

您不应将Content-Type标题设置为application/json. 您可以不设置Content-Type标题,也可以手动将其设置为application/x-www-form-urlencoded.

于 2013-05-17T08:06:45.953 回答