【问题标题】:How to pass custom header to RESTful call?如何将自定义标头传递给 RESTful 调用?
【发布时间】:2012-05-09 21:45:29
【问题描述】:

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

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

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

【问题讨论】:

    标签: php rest http-headers


    【解决方案1】:

    你可以像这样使用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 以获得问题的最佳解决方案;然而,作为一个成熟的替代品,curl 可能值得一提。
    • 在你发布你的答案之前,我一直在输入相同的答案,所以我提供了一个 curl 示例。
    • 我同意 curl 是一个不错的选择(在许多情况下更有用),但在这种情况下我需要使用 file_get_contents。好答案!谢谢!
    • 这个方法可以重定向吗?我能够实现它但无法重定向到“someservice.com/api/fetch?key=1234567890
    【解决方案2】:

    你可以使用 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);
    

    【讨论】:

      【解决方案3】:
      $context = stream_context_create(array(
      'http' => array(
      'method' => 'GET',
      'header' => 'CUSTOM HEADER HERE',
      )
      ));
      
      $result = file_get_contents($url, false, $context);
      

      【讨论】:

        猜你喜欢
        • 2012-11-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-22
        • 2012-10-19
        • 1970-01-01
        相关资源
        最近更新 更多