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

时间:2012-05-09 21:45:30

标签: php rest http-headers

我需要为我的网站连接一些Web服务API。大多数API都包含这样的内容:

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

但是,一个Web服务需要在自定义HTTP标头中设置API密钥。如何向此API网址发出请求并同时传递自定义标头?

3 个答案:

答案 0 :(得分:8)

您可以像这样使用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 :(得分:3)

你可以使用卷曲。例如:

$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);

答案 2 :(得分:0)

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

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