[英]HttpURLConnection sending JSON POST request to Apache/PHP
[英]Sending JSON from Java HTTPUrlConnection, but $_POST variable is empty in PHP?
我正在编写一个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();
}
试试吧。
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变量中获得输出;
我认为缺少同花顺试试os.flush(); 在os.write(..)之后
不要使用$ _POST。 在用户服务器上执行类似的操作
$json = file_get_contents('php://input');
$animals= json_decode($json,true);
//you can do
echo $animals['dog'];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.