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

Jak*_*son 2 php rest http-headers

我需要为我的网站连接一些Web服务API.大多数API涉及到以下内容:

$data = file_get_contents("http://www.someservice.com/api/fetch?key=1234567890
Run Code Online (Sandbox Code Playgroud)

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

ste*_*ewe 9

您可以像这样使用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);
?>
Run Code Online (Sandbox Code Playgroud)