开发者

how to read a response back from URL which is sending the response in json

开发者 https://www.devze.com 2023-03-05 15:37 出处:网络
I have been given an API url feed whi开发者_运维百科ch returns response in JSON format and I have been told to set the headers to this:

I have been given an API url feed whi开发者_运维百科ch returns response in JSON format and I have been told to set the headers to this:

Accept: application/json
X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009

Could anyone please tell me how to move ahead with this problem?


Question 1

I would use the PHP curl libraries.

For example:

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json', 
    'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009',
));

// grab URL and pass it to the browser
echo curl_exec($ch);

// close cURL resource, and free up system resources
curl_close($ch);

See curl_setopt() for more information on the constants such as CURLOPT_HTTPHEADER I have used above.

Question 2 from comments

// create a new cURL resource
$ch = curl_init();

// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json', 
    'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009',
));

// grab URL and pass it to the browser
$json = json_decode(curl_exec($ch), true);

// close cURL resource, and free up system resources
curl_close($ch);

$json now contains an associative array of the response, which you can var_dump()to see the structure.


If you're using cURL in PHP you can do set custom headers on the request with:

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Accept: application/json',
    'X-some-API-Key: fdfdfdfdsgddc43aa96c556eb457b4009'
));
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号