用PHP发出HTTP/1.1请求

eju*_*ker 7 php http

我的代码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);
Run Code Online (Sandbox Code Playgroud)

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

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

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

注意:5.3.0之前的PHP不实现分块传输解码.如果此值设置为1.1,则您有责任遵守1.1.

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

Jon*_*tke 3

在任何一种情况下我都会使用 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);
Run Code Online (Sandbox Code Playgroud)

cURL 将默认使用 HTTP/1.1,除非您使用 指定其他内容 curl_setopt($s,CURLOPT_HTTPHEADER,$headers);,其中 $headers 是一个数组。