如何通过curl为json请求正确设置标头

时间:2018-05-13 17:00:02

标签: php json curl

我是API的新人,Curl和Json。我需要将我的appilcation链接到API。

我要连接的API有一个CURL示例:

curl -v -H "Accept: application/json" -H "Content-type: application/json" -X GET  https://www.api.com -u 'user:token'

我做了一些研究,并提出了这样的要求:

$url = "https://www.api.com";

    $headers = array(
        -H "Accept: application/json",
        -H "Content-type: application/json"
        -u 'Authorization: Basic '. base64_encode("user:token") // <---   
    );

        //initializing curl object
        $curl = curl_init();
        //adding fields to the curl object to enter the site
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);  
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); 
        curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');

        //executing the curl call and getting data back
        $json = curl_exec($curl);

        curl_close($curl); // close the connection
        //echo $json;   
        return $json;

我收到了Json请求,但我仍然不理解API提供的示例。我甚至不知道我是否正在好好卷曲。

有人可以向我解释,如果我做得好,我怎么能解释Curl的例子呢?

1 个答案:

答案 0 :(得分:0)

这不是有效的PHP语法:

$headers = array(
    -H "Accept: application/json",
    -H "Content-type: application/json"
    -u 'Authorization: Basic '. base64_encode("user:token") // <---   
);

你应该改用:

$headers = array(
    'Accept: application/json',
    'Content-type: application/json',
);

对于auth,请使用:

curl_setopt($curl, CURLOPT_USERPWD, $username . ':' . $password);