簡體   English   中英

使用 POST 原始 JSON 數據的 PHP CURL

[英]PHP CURL Using POST Raw JSON Data

我正在使用 PHP curl 進行發布,由於某種原因我無法成功發布表單。

$ch = curl_init();
$headers = [
            'x-api-key: XXXXXX',
            'Content-Type: text/plain'
        ];
$postData = array (
    'data1: value1',
    'data2: value2'
);
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);           
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$server_output = curl_exec ($ch);

當我嘗試在帖子中使用相同的內容時,它可以工作,但不適用於 PHP。

var_dump($server_output) ==> string(67) ""require data1 and data2 or check the post parameters""
var_dump(curl_error($ch)) ==> string(0) ""

如果你想使用Content-type: application/jsonraw數據,你的數據似乎應該是json格式

$ch = curl_init();
$headers  = [
            'x-api-key: XXXXXX',
            'Content-Type: text/plain'
        ];
$postData = [
    'data1' => 'value1',
    'data2' => 'value2'
];
curl_setopt($ch, CURLOPT_URL,"XXXXXX");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postData));           
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result     = curl_exec ($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

如果你想要一個排列和解釋的格式,請參閱下面的代碼。

// Set The API URL
$url = 'http://www.example.com/api';

// Create a new cURL resource
$ch = curl_init($url);

// Setup request to send json via POST`
$payload = json_encode(array(
    'data1' => 'value1',
    'data2' => 'value2'
   )
);

// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);

// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('x-api-key: XXXXXX', 'Content-Type: text/plain'));

// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the POST request
$result = curl_exec($ch);

// Get the POST request header status
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

// If header status is not Created or not OK, return error message
if ( $status !== 201 || $status !== 200 ) {
   die("Error: call to URL $url failed with status $status, response $result, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch));
}

// Close cURL resource
curl_close($ch);

// if you need to process the response from the API further
$response = json_decode($result, true);

我希望這有助於某人

暫無
暫無

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

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