本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

使用 PHP 的 Curl API 请求 - 长响应

发布于2023-09-20 21:26     阅读(307)     评论(0)     点赞(14)     收藏(1)


我尝试通过curl从stats.nba.com获取一些游戏分数信息:

function getGame($gameID)
{
$url = "http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&EndRange=28800&GameID=00" . intval($gameID) . "&RangeType=0&Season=2016-17&SeasonType=Regular+Season&StartPeriod=1&StartRange=0";
$process = curl_init($url);

curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:19.0) Gecko/20100101 Firefox/19.0");
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);

$return = curl_exec($process);
$results = json_decode($return);
curl_close($process);

return $results;
}

在浏览器中,此信息如下所示:

http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&EndRange=28800&GameID=0021600966&RangeType=0&Season=2016-17&SeasonType=Regular+Season&StartPeriod=1&StartRange=0

加载大约需要 1-2 秒。但通过 php 获取信息最多需要 10-12 秒。curl_getinfo() 显示starttransfer_time为 10 秒:

array(26) {
 ["url"]=>
 string(174) "http://stats.nba.com/stats/boxscoretraditionalv2?EndPeriod=10&EndRange=28800&GameID=0021601068&RangeType=0&Season=2016-17&SeasonType=Regular+Season&StartPeriod=1&StartRange=0"
 ["content_type"]=>
 string(31) "application/json; charset=utf-8"
 ["http_code"]=>
 int(200)
 ["header_size"]=>
 int(384)
 ["request_size"]=>
 int(284)
 ["filetime"]=>
 int(-1)
 ["ssl_verify_result"]=>
 int(0)
 ["redirect_count"]=>
 int(0)
 ["total_time"]=>
 float(10.717)
 ["namelookup_time"]=>
 float(0.046)
 ["connect_time"]=>
 float(0.109)
 ["pretransfer_time"]=>
 float(0.109)
 ["size_upload"]=>
 float(0)
 ["size_download"]=>
 float(5455)
 ["speed_download"]=>
 float(509)
 ["speed_upload"]=>
 float(0)
 ["download_content_length"]=>
 float(5455)
 ["upload_content_length"]=>
 float(-1)
 ["starttransfer_time"]=>
 float(10.686)
 ["redirect_time"]=>
 float(0)
 ["redirect_url"]=>
 string(0) ""
 ["primary_ip"]=>
 string(13) "87.245.194.98"
 ["certinfo"]=>
 array(0) {
 }
 ["primary_port"]=>
 int(80)
 ["local_ip"]=>
 string(12) "192.168.1.88"
 ["local_port"]=>
 int(62105)
}

造成这种情况的原因是什么以及如何解决?


解决方案


确实,就像@darker 在评论中指出的那样。看来将以下行添加到您的代码中就可以解决问题。(已测试)。

curl_setopt($process, CURLOPT_HTTPHEADER, array('Expect: 100-continue'));

Expect: 100-continue通常在使用 POST 时似乎是相关的。尽管在您的代码中您使用 GET 而不是 POST,但您使用的 API 似乎被设计为支持其他方式。

在我的研究中,我遇到了一篇文章(下面的链接),它解释了交易如何运作。

引用文章中的话,

包含 Expect: 100-Continue 标头的 API POST 请求可以节省客户端和服务器之间的带宽,因为服务器甚至可以在传输请求正文之前拒绝 API 请求。例如,对于请求正文非常大的 API POST 请求(例如文件上传),服务器可以在发送推送正文之前检查无效身份验证并拒绝请求,从而显着节省带宽。

参考:https://support.urbanairship.com/hc/en-us/articles/213492003--Expect-100-Continue-Issues-and-Risks



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/548966/a4c0bcee89189ca6d045/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

14 0
收藏该文
已收藏

评论内容:(最多支持255个字符)