首頁  >  文章  >  php教程  >  PHP利用curl發起Http請求的400錯誤分析

PHP利用curl發起Http請求的400錯誤分析

巴扎黑
巴扎黑原創
2016-11-07 10:04:0413928瀏覽

摘要: 當http請求出現400錯誤時,一般是http請求無效(bad request),url參數編碼格式不正確導致。而url是有一定格式要求的,一般只能使用英文字母、阿拉伯數字和一些特殊字符,其他字符如空格和雙引號需要經過編碼後才能用戶url。 1.在瀏覽器中直接存取時瀏覽器會自動進行編碼處理 2.但是在程式中直接呼叫時則需要事先對url進行編碼,如php使用curl_exec呼叫時需要對空格等非法字元進行編碼。 3.特別是針對url參數中包含json資料值需要多加註意。

背景

現像一-php封裝的http請求介面呼叫url

PHP利用curl發起Http請求的400錯誤分析

1.response的rawheader值顯示400錯誤

HTTP/1.1 400 Unknown VersionServer: Tengine/2.0.3Date: Tue, 19 Jul 2016 07:38:15 GMTContent-Length: 0Connection: keep-alive

1.response的rawheader值顯示400錯誤

.php封裝的Request物件的send方法

nategood/httpful中的Request::send方法使用php的curl_exec介面發起http請求。

/**
* 发送httpful get请求
* @param  [array] $params [description]
* @return [object]         [description]
*/public  function sendGetRequest($serverUrl,$params){    try{
        $str_params = '';        foreach ($params as $key => $value) {
            $str_params .= "&$key=".$value;
        }
        $response =  \Httpful\Request::get($serverUrl.$str_params)->send();        return  $response->body;
    }catch(Execption $e){        return array("statuscode"=>'-1',"message"=>'服务器出错了');
    }
}

4.curl_exec調用前url值

/**
* Actually send off the request, and parse the response
* @return string|associative array of parsed results
* @throws ConnectionErrorException when unable to parse or communicate w server
*/public function send(){    if (!$this->hasBeenInitialized())        $this->_curlPrep();
    $result = curl_exec($this->_ch);    if ($result === false) {        if ($curlErrorNumber = curl_errno($this->_ch)) {
            $curlErrorString = curl_error($this->_ch);            $this->_error($curlErrorString);            throw new ConnectionErrorException('Unable to connect: ' . $curlErrorNumber . ' ' . $curlErrorString);
        }        $this->_error('Unable to connect.');        throw new ConnectionErrorException('Unable to connect.');
    }
    $info = curl_getinfo($this->_ch);    // Remove the "HTTP/1.x 200 Connection established" string and any other headers added by proxy
    $proxy_regex = "/HTTP\/1\.[01] 200 Connection established.*?\r\n\r\n/s";    if ($this->hasProxy() && preg_match($proxy_regex, $result)) {
        $result = preg_replace($proxy_regex, '', $result);
    }
    $response = explode("\r\n\r\n", $result, 2 + $info['redirect_count']);
    $body = array_pop($response);
    $headers = array_pop($response);
    curl_close($this->_ch);    return new Response($body, $headers, $this, $info);
}

現象二-瀏覽器中直接存取url

PHP利用curl發起Http請求的400錯誤分析

http://192.168.59.146/api?version=1.0&format=json&appkey=KtSNKxk3&access_token=changyanyun&method=pan.file.export&uid=3062000039000412278&fileId=3aaaa5c8-3eaa-4511-91e7-46831d418f10&fileIndex={"lifecycle":{"auditstatus":"0"},"general":{"source":"UGC","creator":"\u6559\u5e080523","uploader":"gsres_iflytek_f968bca78360d38abcbaf23a5a318b12","extension":"ppt","title":"Unit12 What did you do last weekdend\u8bfe\u65f64\uff081\uff09"},"properties":{"subject":["01"],"edition":["01"],"stage":["010001"],"book":["01010101-001"],"unit":["01"],"course":[""],"unit1":["01"],"unit2":[""],"unit3":[""],"phase":["03"],"type":["0100"],"rrtlevel1":["08"]}}

原因分析

現象和現像中的對比url值為json字串

fileIndex參數值中的title屬性值中的空格字元在現象二中被編碼為%20,且雙引號"被編碼為%22,此操作為瀏覽器自動執行

將url中的空格進行編碼後,curl_exec介面返回200

測試代碼

http://192.168.59.146/api?version=1.0&format=json&appkey=KtSNKxk3&access_token=changyanyun&method=pan.file.export&uid=3062000039000412278&fileId=3aaaa5c8-3eaa-4511-91e7-46831d418f10&fileIndex={ %22lifecycle%22:{ %22auditstatus%22:%220%22},%22general%22:{ %22source%22:%22UGC%22,%22creator%22:%22\u6559\u5e080523%22,%22uploader%22:%22gsres_iflytek_f968bca78360d38abcbaf23a5a318b12%22,%22extension%22:%22ppt%22,%22title%22:%22Unit12%20What%20did%20you%20do%20last%20weekdend\u8bfe\u65f64\uff081\uff09%22},%22properties%22:{ %22subject%22:[%2201%22],%22edition%22:[%2201%22],%22stage%22:[%22010001%22],%22book%22:[%2201010101-001%22],%22unit%22:[%2202%22],%22course%22:[%22%22],%22unit1%22:[%2202%22],%22unit2%22:[%22%22],%22unit3%22:[%22%22],%22phase%22:[%2203%22],%22type%22:[%220100%22],%22rrtlevel1%22:[%2208%22]}}

百分號編碼(即url編碼)

一般來說,URL只能使用英文字母、阿拉伯數字和某些標點符號,不能使用其他文字和符號。 !*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL."

"只有字母和數字[0-9a-zA-Z]、一些特殊符號"$-.+!*'(),"[不包括雙引號]、以及某些保留字,才可以不經過編碼直接用於URL。 "

url編碼是特定上下文的統一資源定位符(URL)的編碼機制,伺服器解析http請求時如果遇到非標準字符,會對該非標準字符進行編碼

總結

當http請求出現400錯誤時,一般是http請求無效(bad request),url參數編碼格式不正確導致。引號需要經過編碼後才能用戶url。空格等非法字元進行編碼。
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn