我正在尝试将数据从Android应用程序发送到Web服务器.我的android应用程序正在成功运行.但是php代码有问题.
<?php
$json = $_SERVER['HTTP_JSON'];
echo "JSON: \n";
var_dump($json);
echo "\n\n";
$data = json_decode($json,true);
echo "Array: \n";
var_dump($data);
echo "\n\n";
$name = $data['name'];
$pos = $data['position'];
echo "Result: \n";
echo "Name : ".$name."\n Position : ".$pos;
?>
Run Code Online (Sandbox Code Playgroud)
错误:
Notice: Undefined index: HTTP_JSON in C:\wamp\www\jsonTest.php on line 2
( line 2 : $json = $_SERVER['HTTP_JSON']; )
Run Code Online (Sandbox Code Playgroud)
我找不到这些问题的原因.你能帮助我吗 ?(注意:我正在使用wamp服务器)
以下是相关的Android来源:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("10.0.2.2:90/jsonTest.php";);
JSONObject json = new JSONObject();
try {
json.put("name", "flower");
json.put("position", "student");
JSONArray postjson=new JSONArray();
postjson.put(json);
httppost.setHeader("json",json.toString());
httppost.getParams().setParameter("jsonpost",postjson);
System.out.print(json);
HttpResponse response = httpclient.execute(httppost);
if(response != null)
{
InputStream is = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
text = sb.toString();
}
tv.setText(text);
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
Run Code Online (Sandbox Code Playgroud)
此代码在android端成功运行(无错误).但是php方面有问题..谢谢.
这不是你的JSON所在的地方:
$json = $_SERVER['HTTP_JSON'];
Run Code Online (Sandbox Code Playgroud)
你可能意味着:
$json = $_POST['HTTP_JSON'];
Run Code Online (Sandbox Code Playgroud)
HTTP_JSON您在Android应用中为JSON提供的POST变量名称在哪里.
其余的错误源于json_decode失败的事实,因为您没有成功地从请求中读取JSON数据.您可以检查响应json_decode以检查它是否成功,如下所示:
$data = json_decode($json,true);
if( $data === NULL)
{
exit( 'Could not decode JSON');
}
Run Code Online (Sandbox Code Playgroud)
最后,true作为第二个参数传递json_encode意味着它将返回一个关联数组,因此你可以像这样访问元素:
$name = $data['name'];
$pos = $data['position'];
Run Code Online (Sandbox Code Playgroud)
请务必阅读 json_encode 的文档,以便了解它正在做什么.
编辑:您的问题是您使用$_POST错误的名称访问参数.你应该使用:
$json = $_POST['jsonpost'];
Run Code Online (Sandbox Code Playgroud)
由于以下行命名参数"jsonpost":
httppost.getParams().setParameter("jsonpost",postjson);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6828 次 |
| 最近记录: |