简体   繁体   中英

PHP CURL Using POST Raw JSON Data

I am working with PHP curl for post, for some reason I couldn't post the form successfully.

$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);

When I try using the same in post it works, but not with PHP.

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

If you wanna use Content-type: application/json and raw data, seem your data should be in json format

$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);

If you want an arranged and explained format, see the code below.

// 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);

I hope this helps someone

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM