前端开发
242
HTTP请求是开发的过程中经常会遇到的任务,GET请求比较简单,但是POST请求却会遇到一些问题。有时候对方需要你模拟表单请求,有时候又希望你传递一个json。我们可以封装一个通用的方法来完成。
function post($url, $data = [], $isJson = true, $headers = [], $timeout = 10) { if ($isJson) { $headers['Content-Type'] = 'application/json'; $postFields = json_encode($data); } else { $headers['Content-Type'] = 'application/x-www-form-urlencoded'; $postFields = http_build_query($data); } $headers = formatHeader($headers); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); //设定请求后返回结果 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //忽略证书 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields); // 忽略返回的header头信息 curl_setopt($ch, CURLOPT_HEADER, 0); // 请求头信息 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 设置超时时间 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout); $response = curl_exec($ch); $curlInfo = curl_getinfo($ch); curl_close($ch); return $response; } /** * 对header信息进行格式化处理 * @param $headers * @return array */ function formatHeader($headers) { if (empty($headers)) return []; $result = []; foreach ($headers as $key => $value) { $result[] = "$key:$value"; } return $result; }
模拟表单请求:
$url = 'https://test.com'; $params = [ 'name' => 'guo', 'age' => 25 ]; $result = post($url, $params, true);
发送json数据:
$url = 'https://test.com'; $params = [ 'name' => 'guo', 'age' => 25 ]; $result = post($url, $params, false);
