【发布时间】:2013-10-01 00:53:21
【问题描述】:
在发布这个问题之前我环顾四周,所以如果它在另一个帖子上,我很抱歉,这只是我在这里的第二个问题,所以如果我没有正确格式化这个问题,我很抱歉。
我创建了一个非常简单的 Web 服务,它需要获取 post 值并返回 JSON 编码的数组。这一切都很好,直到我被告知我需要使用 application/json 的内容类型发布表单数据。从那以后,我无法从 Web 服务返回任何值,这肯定与我如何过滤它们的帖子值有关。
基本上在我的本地设置中,我创建了一个执行以下操作的测试页面 -
$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") 和其他一些方法,但我有点摸不着头脑。
任何帮助将不胜感激。
谢谢,史蒂夫
感谢迈克尔的帮助,这是向前迈出的明确一步
更新 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));
正如我所说,至少我现在看到一个响应,而之前它返回一个空白页面
【问题讨论】:
-
不确定失败是什么,但恕我直言,第一步是打印出 $_POST 的内容以查看其中的内容。如果数据在那里,则很容易处理它们。如果 $_POST 为空,至少你知道问题出在哪里。