簡體   English   中英

將帶有PHP和CURL的JSON字符串發布到php頁面並獲取響應

[英]POST JSON string with PHP and CURL to a php page and get response

我正在嘗試學習如何通過CURL將PHP發布到另一個PHP頁面並閱讀響應。

我有2頁。 第一個是test.php

<?php
$array['User'] = array();
$array['User']['AppId'] = 'sdfgfd9-sdfgsdf-sdfgfdgfgff';
$array['User']['UserName'] = 'me@example.co.uk';
$array['User']['Token'] = 'fsdgf5-455g-223ee-bggg-asdsadsda';
$array['User']['Timestamp'] = '2018-05-30BST16:28:293600';

$url = "https://www.myurl.co.uk/api/index.php";    
$content = json_encode($array['User']);

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
array("Content-type: application/json"));
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $content);

$json_response = curl_exec($curl);

$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 201 ) 
{
   die("Error: call to URL $url failed with status $status, response 
  $json_response, curl_error " . curl_error($curl) . ", curl_errno " . 
  curl_errno($curl));
}

curl_close($curl);

$response = json_decode($json_response, true);
echo $response;
?>

然后在頁面上,我只是從中獲取數據。

<?php
$userArray = array();   
$userArray = trim(file_get_contents("php://input"));
echo json_decode($userArray, true);
?>

當我在test.php上運行腳本時,得到的響應是:

Error: call to URL https://www.myurl.co.uk/api/index.php failed with status 200, response Array, curl_error , curl_errno 0

我對錯誤的理解不足,無法理解要進行哪些更改才能使此工作正常進行?

試試:curl_setopt($ curl,CURLOPT_HTTPHEADER,array('method'=>'POST','header'=>'Content-Type:application / json'。“ \\ r \\ n”。'Content-Length:'。strlen ($ data_string)。“ \\ r \\ n”,'content'=> $ data_string,);

或類似

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM