从Android发送HttpPost请求,从PHP读取Post

时间:2013-07-08 11:36:36

标签: java php android http post

当我在一些业余时间进行Android学习时,我遇到了HttpPost请求的奇怪行为。

我想要实现的目标: 从Android应用程序向我的开发PC上运行的Apache Web服务器发出简单的POST请求,并显示发送表单的PHP脚本的POSTed数据。

我的Android应用 Java代码位于Activity AsyncTask内,如下所示:

private class DoSampleHttpPostRequest extends AsyncTask<Void, Void, CharSequence> {

    @Override
    protected CharSequence doInBackground(Void... params) {
        BufferedReader in = null;
        String baseUrl = "http://10.0.2.2:8080/android";

        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost request = new HttpPost(baseUrl);

            List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("login", "someuser"));
            postParameters.add(new BasicNameValuePair("data", "somedata"));
            UrlEncodedFormEntity form = new UrlEncodedFormEntity(postParameters);
            request.setEntity(form);

            Log.v("log", "making POST request to: " + baseUrl);

            HttpResponse response = httpClient.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            return sb.toString();
        } catch (Exception e) {
            return "Exception happened: " + e.getMessage();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void onPostExecute(CharSequence result) {
        // this refers to a TextView defined as a private field in the parent Activity
        textView.setText(result);
    }

}

我的 PHP代码如下:

<?php
echo "Hello<br />";
var_dump($_SERVER);
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    echo "Page was posted:<br />";
    foreach($_POST as $key=>$var) {
        echo "[$key] => $var<br />";
    }
}
?>

最后问题: 正如您所看到的,$_SERVER内容被转储,而输出$_SERVER["REQUEST_METHOD"]中的值GET尽管我实际上正在发出POST请求。即使我尝试转储$_POST的内容,它也是空的。

我做错了什么?提前致谢。

1 个答案:

答案 0 :(得分:2)

您可能需要在网址末尾指定一个尾部斜杠。

Apache经常重定向不以尾部斜杠结尾的请求,以便它们包含尾部斜杠。该重定向是一个GET重定向(没有一些调整),因此所有POST数据都会丢失。