我在发布此问题之前四处张望,所以很抱歉在另一个帖子上,这只是我的第二个问题,如果我没有正确设置此问题的格式,请您道歉。
我创建了一个非常简单的Web服务,该服务需要获取发布值并返回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”)和许多其他方式,但是我在黑暗中开枪了。
任何帮助将不胜感激。
谢谢,史蒂夫
感谢Michael的帮助,这是一个明确的进步,当我回应该帖子时,我现在至少得到了回应...即使它为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));
正如我所说,至少我现在看到一个回应,当时它在返回空白页之前
你有空$_POST
。如果您的网络服务器希望以json格式查看数据,则需要读取原始输入,然后使用JSON解码对其进行解析。
您需要这样的东西:
$json = file_get_contents('php://input');
$obj = json_decode($json);
另外,您使用错误的代码来测试JSON通讯...
CURLOPT_POSTFIELDS
告诉curl
您将参数编码为application/x-www-form-urlencoded
。您需要在这里使用JSON字符串。
更新
您的测试页php代码应如下所示:
$data_string = json_encode($data);
$ch = curl_init('http://webservice.local/');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
$result = json_decode($result);
var_dump($result);
同样,在您的Web服务页面上,您应该删除其中一行header('Content-type: application/json');
。它只能被调用一次。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句