如何将自定义标头传递给RESTful调用?

3

我需要连接一些Web服务API,用于我的网站。其中大部分API都涉及类似于以下内容:

$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890

但是有一个网络服务需要将API密钥设置在自定义的HTTP头中。我该如何在请求API URL时同时传递自定义头?

4个回答

11
你可以像这样使用stream_context_create
<?php
$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"CustomHeader: yay\r\n" .
              "AnotherHeader: test\r\n"
  )
);
$context=stream_context_create($options);
$data=file_get_contents('http://www.someservice.com/api/fetch?key=1234567890',false,$context);
?>

1
对于这个问题,最佳解决方案是+1;然而,值得一提的是curl作为一个完整的替代方案。 - cmbuckley
我正在打字写相同的答案,直到你发表了你的答案,所以我提供了一个curl的例子。 - Rob
我同意curl是一个很好的选择(在许多情况下更有用),但在这种情况下我需要使用file_get_contents。好答案!谢谢! - Jake Wilson
这种方法能够实现重定向吗?我可以实现它,但无法重定向到"http://www.someservice.com/api/fetch?key=1234567890"。 - Tanmoy Bhattacharjee

4
你可以使用curl。例如:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.someservice.com/api/fetch?key=1234567890');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Header: value'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$result = curl_exec($ch);
curl_close($ch);

0
$headers = array(
   "Accept: application/json",
   "Content-Type: application/json",
   "Authorization: 42|W3hpHwxdYXSgOVRDsi7AD8Wg4pEKHebBey0AWpzH"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

0
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'CUSTOM HEADER HERE',
)
));

$result = file_get_contents($url, false, $context);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接