【发布时间】:2012-12-16 11:21:15
【问题描述】:
我正在编写一个 Android 应用程序,我想将一些 JSON 数据发送到 PHP 服务器。 POST 请求确实会发送到服务器,但在我的 server.php 脚本中,我检查了 $_POST 变量,它是空的。 TCP/IP 监视器不在 Eclipse ADT 中,wireshark 不显示 localhost 请求,所以我看不到实际发送的内容。那么有没有人知道正在发送什么以及如何在 PHP 中访问它?还是我在某处的代码中犯了错误?
JSONObject json = new JSONObject();
try {
json.put("dog", "cat");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpURLConnection urlConnection = null;
try {
URL url = new URL("http://10.0.2.2/server.php");
urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
OutputStreamWriter os = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
os.write(json.toString());
os.close();
}
【问题讨论】:
-
你从服务器得到什么响应?
-
检查 $_REQUEST 看看你得到了什么。
-
@t0s 它正在将 server.php 页面的 HTML 发回给我。
-
代码看起来不错...从charlesproxy.com/download 获取Charles 监控软件,并将其代理设置为指向您的Web 服务器。这应该允许您捕获 localhost 请求并查看其内容。
-
有人删除了他们对我的回复......他们的回复是正确的,一旦我设置了 urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") 数据是出现在服务器上。