在php中我們經常用到curl拓展來進行模擬post、get請求,下面就來具體說說怎麼模擬:
初始化curl
curl_setopt($curl, curlopt_url, $url
); curl_setopt(
$curl, curlopt_header, 0); //
過濾http頭
curl_setopt($curl, curlopt_returntransfer, 1); //
顯示輸出結果
curl_setopt($curl, curlopt_post, true); //
post方式
curl_setopt($curl, curlopt_postfields, $post_str); //
post傳輸資料
curl_setopt($curl, curlopt_connecttimeout, 5); //
設定等待時間
curl_setopt($curl,curlopt_timeout,$timeout); //
設定超時
返回內容
返回狀態碼
curl_close($curl
);
if($status=='200') return
$content
;
else
return
false
;}
模擬get請求就很簡單了,直接將post方式改為false,將post傳輸資料項注釋;然後將請求的引數拼接到路徑後面就可以了。
上面這種方式如果我們傳送陣列 或者 a=1&b=2 這樣格式的字串,接受這樣的傳送,直接用$_post 或者$_request就可以獲取對應引數的值,至於其他的怎麼下面再說。
但有時候我們想要傳送json和檔案時上面這種方式可能就有點行不通,需要像下面一樣該改變請求頭
請求json資料:
宣告請求的內容為json
$header = "content-length:".strlen(json_encode($data));//
請求內容的長度
上傳檔案:
$header = "content-type:multipart/form-data";//用$_files接受傳送的檔案
請求html資料:
$header = "content-type:text/html;charset=utf-8";
請求xml資料:
$header = "content-type:text/xml;charset=utf-8";
還有一種:這種方式,如果瀏覽器接受到內容,會直接當做純文字,不會進行html或者xml解析。
$header = "content-type:text/plain;charset=utf-8";1、陣列或者a=1&b=2類的字串
這個不用多說直接用我們常用的$_get、$_post、$_request就可以接受
2、json、xml、html或者其他字串
$xml = file_get_contents("php://input");//或者
php://input 允許讀取 post 的原始資料。和$globals['http_raw_post_data'] 比起來,它給記憶體帶來的壓力較小,並且不需要任何特殊的 php.ini 設定。同時兩者皆不能用於接收enctype="multipart/form-data"形式的資料。
function post($url, $content)
這種方式也可以快速模擬post、get請求,不過這種方式在訪問量不大的情況下還沒什麼問題,如果訪問量大可能就會出問題;所以一般在專案中不太推薦這種請求方式。
使用curl 命令模擬POST GET請求
在進行web後台程式開發測試過程中,常常會需要傳送url進行測試,使用curl可以方便地模擬出符合需求的url命令 假設目標url 為 127.0.0.1 8080 login 使用curl傳送get請求 curl protocol address port url?args plain view ...
使用curl 命令模擬POST GET請求
在進行web後台程式開發測試過程中,常常會需要傳送url進行測試,使用curl可以方便地模擬出符合需求的url命令 假設目標url 為 127.0.0.1 8080 login 使用curl傳送get請求 curl protocol address port url?args 模擬get請求 加上引...
使用curl 命令模擬POST GET請求
在進行web後台程式開發測試過程中,常常會需要傳送url進行測試,使用curl可以方便地模擬出符合需求的url命令 假設目標url 為 127.0.0.1 8080 login 使用curl傳送get請求 curl protocol address port url?args plain view ...