1. 程式人生 > 其它 >詭異的php curl error Empty reply from server

詭異的php curl error Empty reply from server

用Curl類呼叫遠端介面時發現無返回結果,本地瀏覽器呼叫正常,懷疑是伺服器網路原因,執行命令

curl 'http://xxxx.com/?action=abc' 

發現可以獲取到正常返回值,非常詭異,這下不解了,查資料後發現,原來php curl使用的liburl在傳送資料時,如果資料量大於1KB時,會先發送包含header Expect:100-continue的請求與遠端伺服器協商,得到能夠繼續接收資料的確認後才開始傳送真正資料,如果遠端伺服器沒有正確返回,則此次請求失敗,當然也就獲取不到返回結果了。

RFC關於Expect:100-continue的說明:http://www.w3.org/Protocols/rfc2616/rfc2616-sec8.html#sec8.2.3

The purpose of the 100 (Continue) status (see section10.1.1) is to allow a client that is sending a request message with a request body to determine if the origin server is willing to accept the request (based on the request headers) before the client sends the request body. In some cases, it might either be inappropriate or highly inefficient for the client to send the body if the server will reject the message without looking at the body.

Expect:100-continue 在HTTP/1.1中得到支援

綜上,解決方法有兩個:

1.禁用Expect

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Expect:'));

2.使用HTTP/1.0

curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);

原文地址:https://aiddroid.com/solution-for-php-curl-empty-reply-from-server/