我需要连接一些Web服务API,用于我的网站。其中大部分API都涉及类似于以下内容:
$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890
但是有一个网络服务需要将API密钥设置在自定义的HTTP头中。我该如何在请求API URL时同时传递自定义头?
我需要连接一些Web服务API,用于我的网站。其中大部分API都涉及类似于以下内容:
$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890
但是有一个网络服务需要将API密钥设置在自定义的HTTP头中。我该如何在请求API URL时同时传递自定义头?
<?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);
?>
$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);
$headers = array(
"Accept: application/json",
"Content-Type: application/json",
"Authorization: 42|W3hpHwxdYXSgOVRDsi7AD8Wg4pEKHebBey0AWpzH"
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'CUSTOM HEADER HERE',
)
));
$result = file_get_contents($url, false, $context);
file_get_contents
。好答案!谢谢! - Jake Wilson