通过cURL API在PHP中发送JSON:格式错误的JSON

时间:2019-06-24 13:15:32

标签: php json curl confluence confluence-rest-api

我正在尝试通过REST API将数据发送到Confluence,以在此处创建问题。因此,我需要将JSON中的数据发送到服务器。到目前为止,我总是收到HTTP 400作为响应。 使用json_last_error(),我发现我的$ jsonData中的JSON格式错误。我为此找到的唯一更正方法是将“替换为”。我尝试过,但仍然无法使用。您还有其他提示吗?谢谢您!

<?php

//API Url
$url = 'https://***.net/confluence/rest/questions/1.0/question';

//Initiate cURL
$ch = curl_init($url);

//The JSON data
$jsonData = array(
"title" => "abc",
"body" => "def",
"dateAsked" => "2019-06-06",
"spaceKey" => "LMLMLM"
);

//The JSON header
$jsonHeader = array (
'Accept: application/json',
'Content-Type: application/json',
'Authorization: Basic ***'
);

//Encode the array into JSON
$jsonDataEncoded = json_encode ($jsonData);

//Tell cURL that we want to send a POST request
curl_setopt ($ch, CURLOPT_POST, 1);

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

curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);

//Attach Header
curl_setopt ($ch, CURLOPT_HTTPHEADER, $jsonHeader);

//Execute the request
$json_response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
    die("Error: call to URL $ch failed with status $status, response 
$json_response, curl_error " . curl_error($ch) . ", curl_errno " . 
curl_errno($ch));
}

curl_close ($ch);

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

0 个答案:

没有答案