代码之家  ›  专栏  ›  技术社区  ›  ejunker

用PHP发出HTTP/1.1请求

  •  7
  • ejunker  · 技术社区  · 15 年前

    我的代码正在使用 file_get_contents() 向API端点发出GET请求。看起来它在用 HTTP/1.0 我的系统管理员说我需要使用 HTTP/1.1 . 我怎么做一个 HTTP/1.1 请求?我需要使用卷发还是有更好/更容易的方法?

    更新

    我决定使用curl,因为我使用的是php 5.1.6。我这样做最终迫使HTTP/1.1:

    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    

    如果我使用5.3或更高版本,我会尝试这样做:

    $ctx = stream_context_create(array(
        'http' => array('timeout' => 5, 'protocol_version' => 1.1)
        ));
    $res = file_get_contents($url, 0, $ctx);
    echo $res;
    

    http://us.php.net/manual/en/context.http.php

    注意:5.3.0之前的php没有 实现分块传输解码。 如果该值设置为1.1,则为 遵守1.1的责任。

    我发现的另一个可能提供HTTP/1.1的选项是使用 HTTP extension

    2 回复  |  直到 8 年前
        1
  •  3
  •   Jonatan Littke Yukiup    15 年前

    在这两种情况下,我都会使用curl,它提供了更多的控制权,特别是它提供了超时选项。在调用外部API时,这一点非常重要,以免在远程API关闭时让应用程序冻结。

    可以这样:

    # Connect to the Web API using cURL.
    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, 'http://www.url.com/api.php?123=456'); 
    curl_setopt($ch, CURLOPT_TIMEOUT, '3'); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    $xmlstr = curl_exec($ch); 
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    
    curl_close($ch);
    

    默认情况下,curl将使用http/1.1,除非您使用 curl_setopt($s,CURLOPT_HTTPHEADER,$headers); ,其中$headers是一个数组。

        2
  •  2
  •   phihag    8 年前

    只是为了让其他想使用流上下文创建/文件获取内容的人知道,如果您的服务器配置为使用保持活动连接,则响应将不会返回,您需要添加 'protocol_version' => 1.1 以及 'header' => 'Connection: close' .

    下面的例子:

    $ctx = stream_context_create(array(
                   'http' => array(
                      'timeout' => 5,
                      'protocol_version' => 1.1,
                      'header' => 'Connection: close'
                    )
                  ));
    $res = file_get_contents($url, 0, $ctx);
    
    推荐文章