この質問を投稿する前によく調べたので、別の投稿にある場合はお詫びします。これはここでの2番目の質問にすぎないため、この質問を正しくフォーマットしていない場合はお詫びします。
投稿値を受け取り、JSON エンコードされた配列を返す必要がある非常に単純な Web サービスを作成しました。application/json の content-type でフォームデータを投稿する必要があると言われるまで、それはすべてうまくいきました。それ以来、私は 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);
Webサービスにはこれがあります(一部の機能を削除しました)-
<?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_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));
少なくとも私が言うように、以前は空白のページが返されていたのに対し、今では応答が表示されます