PHP CURL使用POST Raw JSON数据

Pra*_*van 5 php json curl raw-post

我正在使用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);
Run Code Online (Sandbox Code Playgroud)

当我尝试在帖子中使用相同的工作,但不是PHP.

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

小智 8

如果您想使用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);
Run Code Online (Sandbox Code Playgroud)

  • 为什么你的答案是文本/纯文本? (3认同)

nen*_*uel 8

如果您想要安排和解释的格式,请参阅下面的代码。

// 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: application/json'));

// 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);
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助别人

  • 检查状态应该是 `if (!$status || !($st​​atus == 201 || $status == 200)) {` (2认同)