不发送POST参数

时间:2012-10-05 10:48:01

标签: java android http-post

我尝试了几件事但我的Android应用程序没有发送帖子参数。我在虚拟设备上运行应用程序。这是代码:

@Override
public void run() {
    try{
        HttpClient client = new DefaultHttpClient();  
        HttpPost post = new HttpPost(page);   

        HttpParams httpParams = client.getParams();
        httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);

        post.setHeader("Content-type", "application/json");
        post.setHeader("Accept", "application/json");
        JSONObject obj = new JSONObject();
        obj.put("username", "abcd");
        obj.put("password", "1234");
        post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
        HttpResponse response = client.execute(post);
        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader reader = new BufferedReader(isr);
        String line = "";
        while((line = reader.readLine()) != null){
            System.out.println(line);
        }
    }catch(Exception e){
        e.printStackTrace();
    }
}

它应该发送一个帖子请求到PHP页面。此页面显示POST阵列的输出:

<?php
print_r($_POST);
?>

当我运行应用程序时,它会显示一个空数组。

3 个答案:

答案 0 :(得分:1)

那是因为你正在发送JSON

标准php $ _POST是从键值对构建的 所以你应该发布key1 = value1&amp; key2 = value2

或者您应该阅读

$HTTP_RAW_POST_DATA

<?php $postdata = file_get_contents("php://input"); ?> 

并使用

json_decode( $postdata );

PHP不会自动为你解码json

你也可以使用另一种方法和POST你的json,如data = YourJsonCode

然后使用json_decode($ _POST ['data'])对其进行解码;

答案 1 :(得分:0)

尝试发送url编码的名称/值对。您也可以使用EntityUtils将响应转换为String

HttpClient client = new DefaultHttpClient();  
HttpPost post = new HttpPost(page);

HttpParams httpParams = client.getParams();
httpParams.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);

post.setHeader("Content-Type","application/x-www-form-urlencoded");

List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("username", "abcd"));
formParams.add(new BasicNameValuePair("password", "1234"));

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams,HTTP.UTF_8);
post.setEntity(entity);
HttpResponse httpResponse = client.execute(post);
System.out.println(EntityUtils.toString(httpResponse.getEntity()));

答案 2 :(得分:0)

问题解决了。有一个htaccess文件重定向所有非www页面。