当我在业余时间学习 Android 时,我遇到了一个奇怪的HttpPost
请求行为。
我想要实现的目标: 从 Android 应用程序向在我的开发 PC 上运行的 Apache Web 服务器发出一个简单的 POST 请求,并显示来自表单发送到的 PHP 脚本的 POST 数据。
我的 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
,它也是空的。
我究竟做错了什么?提前致谢。