我需要为我的网站连接一些web服务API。大多数API都包含如下内容:
$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890但有一个web服务需要在自定义HTTP标头中设置API密钥。如何向此接口url发出请求,并同时传递自定义头部?
发布于 2012-05-10 05:50:10
您可以像这样使用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);
?>发布于 2012-05-10 05:52:42
您可以使用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);发布于 2012-05-10 05:55:36
$context = stream_context_create(array(
'http' => array(
'method' => 'GET',
'header' => 'CUSTOM HEADER HERE',
)
));
$result = file_get_contents($url, false, $context);https://stackoverflow.com/questions/10524543
复制相似问题