如何连接到Companies House API - 具有特定的curl标头和API密钥要求?

时间:2016-08-18 09:03:51

标签: javascript php api curl

我正在尝试连接到UK Companies House API。理想情况下,我正在寻找JavaScript解决方案。

但是我试图让这个PHP变种运行起来。如何使用API​​密钥访问API?

PHP:

public function GetCompanyHouse(){

        $int = '00928555';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'http://data.companieshouse.gov.uk/doc/company/' . $int . '.json'); 
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_TIMEOUT, '10');

        $result = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        switch($status)
        {
            case '200':
                return json_decode($result);
                break;

            default:
                return false;
                break;
        }


    }

https://developer.companieshouse.gov.uk/api/docs/index/gettingStarted/apikey_authorisation.html

curl -XGET -u my_api_key: 

https://api.companieshouse.gov.uk/company/00000006

我是否将其设置为标题?

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'u: my_api_key'
    ));

是否可以像这样进行JSON调用? https://api.companieshouse.gov.uk/company/00000006?api_key=xxxxxx

这是一个正在运行的jQuery模型

http://jsfiddle.net/NYEaX/1412/

$(document).ready(function() {
  console.log("api");


xhr = new XMLHttpRequest();

$(document).ready(function() {
  $.ajax({
    url: 'https://api.companieshouse.gov.uk/search?q=subway',
    type: 'GET',
    datatype: 'json',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader       
  });   
});

function setHeader(xhr) {

  xhr.setRequestHeader('Authorization', 'Basic bXlfYXBpX2tleTo=');
//  xhr.setRequestHeader('X-GET', 'xx');
}  

});

1 个答案:

答案 0 :(得分:0)

对我来说 curl -u“token”:https://api.companieshouse.gov.uk/company/SC185088 在命令提示符下工作