在发布这个问题之前,我浏览了很多内容,所以如果这个问题已经在其他帖子中出现,那么请原谅,这是我在这里的第二个问题,所以如果我没能正确格式化这个问题,请原谅。
我创建了一个非常简单的 Web 服务,需要接收 post 值并返回 JSON 编码数组。一切都很顺利,直到有人告诉我我需要使用 content-type 为 application/json 发送表单数据。从那时起,我就无法从 Web 服务返回任何值,这明显与我如何过滤他们的 post 值有关。
基本上,在我的本地设置中,我创建了一个测试页面,执行以下操作 -
$curl = curl_init();
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data))
);
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/'); // Set the url path we want to call
$result = curl_exec($curl);
//see the results
$json=json_decode($result,true);
curl_close($curl);
print_r($json);
在我们的网络服务中,我有如下代码(已删除一些函数)-
<?php
header('Content-type: application/json');
/* connect to the db */
$link = mysql_connect('localhost','root','root') or die('Cannot connect to the DB');
mysql_select_db('webservice',$link) or die('Cannot select the DB');
if(isset($_POST['action']) && $_POST['action'] == 'login') {
$statusCode = array('statusCode'=>1, 'statusDescription'=>'Login Process - Fail');
$posts[] = array('status'=>$statusCode);
header('Content-type: application/json');
echo json_encode($posts);
/* disconnect from the db */
}
@mysql_close($link);
?>
基本上,我知道这是由于$_POST的值未被设置,但我找不到需要替换$_POST的内容。我尝试了json_decode($_POST)、file_get_contents("php://input")和其他一些方法,但有点盲目。
如果有任何帮助,将不胜感激。
谢谢,Steve
感谢Michael的帮助,这是一个明显的进步,当我回显post时,我现在至少得到了一个响应....即使它是null
更新的CURL -
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_URL, 'http://webservice.local/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
更新了接收数据页面的 PHP 版本 -
$inputJSON = file_get_contents('php://input');
$input= json_decode( $inputJSON, TRUE ); //convert JSON into array
print_r(json_encode($input));
至少现在我能看到有回应了,而之前它只会返回一张空白页面。