dqspy04266
2011-05-12 12:37 阅读 37

如何从在json中发送响应的URL读取响应

I have been given an API url feed which 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?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dreamworld2007 dreamworld2007 2011-05-12 12:43

    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.

    点赞 评论 复制链接分享
  • dou6495 dou6495 2011-05-12 12:43

    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'
    ));
    
    点赞 评论 复制链接分享

相关推荐