PHP中的HTTP请求(GET请求,POST请求),及response响应返回
不说了,直接记录代码,下次直接用。
get请求:
/**
* GET请求
* @param $url
* @return mixed
*/
public function curlGet($url){
$ch1 = curl_init();
$timeout = 0;
curl_setopt($ch1, CURLOPT_URL, $url);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch1, CURLOPT_ENCODING, '');
curl_setopt($ch1, CURLOPT_MAXREDIRS, 10);
curl_setopt($ch1, CURLOPT_HTTPHEADER, array());
curl_setopt($ch1, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch1, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch1, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$access_txt = curl_exec($ch1);
curl_close($ch1);
return json_decode($access_txt, true);
}
post请求:
/**
* 发送http post请求
* @param $url
* @param $data
* @param array $header
* @param bool $is_json
* @return mixed|string
*/
function httpPost($url, $data, $header = [],$is_json = true)
{
if (empty($header)) {
$header = array(
"Accept: application/json",
"Content-Type:application/json;charset=utf-8",
);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$res = curl_exec($ch);
if (curl_errno($ch)) {
$error_message = curl_error($ch);
@file_put_contents(storage_path('logs/error.log'), var_export($error_message, true) . PHP_EOL, FILE_APPEND);
}
curl_close($ch);
if($is_json){
return json_decode($res, true);
}
return trim($res);
}
response响应返回(记录日常用的下次直接用了):
/**
* 响应
* @param null $msg
* @param int $code
* @param array $data
* @param int $result_code
* @param string $type
* @return void
*/
public function response($msg = null,$code = self::SUCCESS,$data = [],$result_code = 200,$type = 'application/json')
{
$result = [
'msg' => $msg,
'code' => $code,
'data' => $data,
];
$this->header['Content-Type'] = $type;
$response = response($result,$result_code,$this->header);
throw new HttpResponseException($response);
}
/**
* @param array $data
* @param string $message
* @param int $status
* @return string
*/
protected function success($data = [], $message = 'success', $status = 200)
{
$array = compact('status', 'message', 'data');
return json_encode($array, JSON_UNESCAPED_UNICODE);
}
/**
* @param int $status
* @param string $message
* @param array $data
* @return string
*/
protected function error($message = 'error', $status = 400, $data = [])
{
$array = compact('status', 'message', 'data');
return json_encode($array, JSON_UNESCAPED_UNICODE);
}
还没有评论,快来发表第一个评论吧