如何以json格式设置请求主体

时间:2016-10-04 12:24:14

标签: php json api

我试图以json格式向API发送请求正文。文档声明身体需要格式化如下:

//Request body needs to the contain a JSON object in the following format:

{  
  "delete_list":[  
    "8fcd1d68c82dd39d65ef8ea9a7948bbe",
    "8bca1d68c92dd39d65ef8ea9a7948bbe",
    "8bca1d69c82d939d65ef8ea9a7948bbe",
    "8bca1d69c82d939d65ef8ea9a7947bbe"
   ]
}

我尝试过的代码似乎失败了,我不知道为什么。我已经尝试了很多调整,似乎没有任何工作:

    $del = array("delete_list" => "[8bca1d69c82d939d65ef8ea9a7947bbe]");
    $j = json_encode($del);


    $apiToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

    $httpHeadersArray = Array();
    $httpHeadersArray[] = 'Authorization: key='.$apiToken;
    $httpHeadersArray[] = 'Content-Type: application/json';


    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    #curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($j));
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);


    $res = curl_exec($ch);


    echo "<pre>";
    print_r($res);
    echo "</pre>";

我从API返回的最终结果如下:

{"status":"failure","message":"JSON malformed"}

有关我的代码错误的建议吗?这将不胜感激。谢谢!

4 个答案:

答案 0 :(得分:2)

两件事:

1)您使用单个字符串对json进行编码,但您需要使用数组对对象进行编码。

2)您正在使用http_build_query来对数组参数进行urlencode并破坏JSON结构。

这样做:

    $del = array("delete_list" => [ "8bca1d69c82d939d65ef8ea9a7947bbe" ]);
    $j = json_encode($del);


    $apiToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';

    $httpHeadersArray = Array();
    $httpHeadersArray[] = 'Authorization: key='.$apiToken;
    $httpHeadersArray[] = 'Content-Type: application/json';


    //open connection
    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    #curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
    curl_setopt($ch, CURLOPT_POSTFIELDS, $j);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeadersArray);


    $res = curl_exec($ch);


    echo "<pre>";
    print_r($res);
    echo "</pre>";

答案 1 :(得分:1)

将标题放在顶部

header('Content-Type: application/json');

答案 2 :(得分:1)

是的,你正在使json或数组

变形

$del = array("delete_list" => array("8bca1d69c82d939d65ef8ea9a7947bbe")); $j = json_encode($del);

这是正确的方法,您将数组作为字符串传递,这将无法正常工作。

答案 3 :(得分:0)

  

json_encode()返回一个包含值的JSON表示的字符串。

     

- PHP Manual

返回值的表示。

print_r(array(
    "delete_list" => "[8bca1d69c82d939d65ef8ea9a7947bbe]"
));

打印:

{
    "delete_list": "[8bca1d69c82d939d65ef8ea9a7947bbe]"
}

鉴于:

print_r(array(
    "delete_list" => array(
        "8bca1d69c82d939d65ef8ea9a7947bbe"
    )
));

打印:

{
    "delete_list": [
        "8bca1d69c82d939d65ef8ea9a7947bbe"
    ]
}