php使用curl請求設定CURLOPT_HTTPHEADER為x-www-form-urlencoded時請求資料
之前做一個專案,和第三方平臺對接,對方要求使用Content-type為x-www-form-urlencoded傳送資料,
我依照國際慣例 把自己之前寫的 curl請求搬過來,
附上自己的curl方法
/** * curl_get_contents * @param mixed $url 請求url * @param mixed $ispost 是否是post請求 * @param mixed $post_data post請求資料 * @return mixed $output 返回資料 * @author winter * 2017年6月15日09:48:52 */ function curl_get_contents($url = '', $ispost = 0, $post_data = array()) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // 對認證證書來源的檢查 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // 從證書中檢查SSL加密演算法是否存在 curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模擬使用者使用的瀏覽器 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // 使用自動跳轉 curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // 自動設定Referer curl_setopt($ch, CURLOPT_TIMEOUT, 10); // 設定超時限制防止死迴圈 curl_setopt($ch, CURLOPT_HEADER, 0); // 查詢顯示返回的Header區域內容 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // 獲取的資訊以檔案流的形式返回 if ($ispost) { curl_setopt($ch, CURLOPT_POST, $ispost); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); } $output = curl_exec($ch); curl_close($ch); return $output; } 然後按網上收到的方法 加上這句話
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); 發現不行。。。。然後又各種搜各種各樣的header。。。都屎了。 無奈還是去官網看看吧。 雖然 一堆英文不好看,但是卻說的很明白 意思搭眼一看 就明白了 原來 from-data用array格式傳送, content-type為x-www-form-urlencoded時用key=value&key=value的形式傳送 看到這 立馬回去改data 完成oK!