从Java HTTPUrlConnection发送JSON,但$\u POST变量在PHP中为空?
我正在编写一个Android应用程序,我想向PHP服务器发送一些JSON数据。POST请求确实会发送到服务器,但在我的server.php脚本中,我检查了$\u POST变量,它是空的。TCP/IP监视器不在EclipseADT中,wireshark不显示localhost请求,所以我看不到实际发送的内容。那么,有没有人知道发送的是什么,以及我如何在PHP中访问它?还是我在某个地方犯了错误从Java HTTPUrlConnection发送JSON,但$\u POST变量在PHP中为空?,java,php,android,json,Java,Php,Android,Json,我正在编写一个Android应用程序,我想向PHP服务器发送一些JSON数据。POST请求确实会发送到服务器,但在我的server.php脚本中,我检查了$\u POST变量,它是空的。TCP/IP监视器不在EclipseADT中,wireshark不显示localhost请求,所以我看不到实际发送的内容。那么,有没有人知道发送的是什么,以及我如何在PHP中访问它?还是我在某个地方犯了错误 JSONObject json = new JSONObject(); try {
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();
}
我想他错过了同花顺 尝试os.flush();在操作系统之后写入(…)试试
JSONObject json = new JSONObject();
try {
json.put("dog", "cat");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient localDefaultHttpClient=new DefaultHttpClient();
HttpPost lotlisting = new HttpPost("http://10.0.2.2/server.php");
ArrayList localArrayList = new ArrayList();
localArrayList.add(new BasicNameValuePair("json",json.toString()));
try {
lotlisting.setEntity(new UrlEncodedFormEntity(localArrayList));
String str = EntityUtils.toString(localDefaultHttpClient.execute(lotlisting).getEntity());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
您将获得str变量中的输出 不要使用$\u POST。在用户服务器上执行类似操作
$json = file_get_contents('php://input');
$animals= json_decode($json,true);
//you can do
echo $animals['dog'];
您从服务器得到了什么响应?检查$\u请求以查看您得到了什么。@t0s它正在将server.php页面的HTML发送给我。代码看起来不错。。。从中获取Charles监控软件,并设置其代理以指向您的web服务器。这应该允许您捕获本地主机请求并查看其内容。有人删除了他们对我的响应…在我设置urlConnection后,他们的响应是正确的。setRequestProperty(“内容类型”,“应用程序/x-www-form-URLCoded”)数据将显示在服务器上。