gpt4 book ai didi

php - 使用 PHP 发出 HTTP/1.1 请求

转载 作者:可可西里 更新时间:2023-11-01 12:56:16 27 4
gpt4 key购买 nike

我的代码使用 file_get_contents() 向 API 端点发出 GET 请求。看起来它正在使用 HTTP/1.0,我的系统管理员说我需要使用 HTTP/1.1。如何发出 HTTP/1.1 请求?我需要使用 curl 还是有更好/更简单的方法?

更新

我决定使用 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

Note: PHP prior to 5.3.0 does notimplement chunked transfer decoding.If this value is set to 1.1 it is yourresponsibility to be 1.1 compliant.

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

最佳答案

在任何一种情况下我都会使用 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 是一个数组。

关于php - 使用 PHP 发出 HTTP/1.1 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2684860/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com