[英]Curl API Request with PHP - long response
我嘗試通過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;
}
在瀏覽器中,此信息如下所示:
並且需要大約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
首先,您需要通過請求標頭詢問服務器的壓縮響應。
其次,對於您的特定URL而言,服務器依賴於Accept-Language:
標頭來快速響應。
以下行將使您的響應更快。
curl_setopt($process, CURLOPT_HTTPHEADER, array("Accept-Language: en-US,en;q=0.8,bn;q=0.6"));
curl_setopt($process,CURLOPT_ENCODING , ""); // Means handle all encodings
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.