curl post与get请求
get 请求 [常用]
// curl初始化
$ch = curl_init($url);
// 设置 curl 参数
// 将头部文件的信息作为数据流输出
curl_setopt($ch, CURLOPT_HEADER, false);
// 执行 curl
$ret = curl_exec($ch);
// curl 关闭请求
curl_close();
post 请求[常用]
// curl初始化
$ch = curl_init($url);
// 设置 curl 参数
// 将头部文件的信息作为数据流输出
curl_setopt($ch, CURLOPT_HEADER, false);
// post 请求
curl_setopt($ch, CURLOPT_POST. true);
// post 传参
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonStr);
// 设置头部信息 [get 方式一般不用]
$headerArr = [
'Content-Type: application/json',
'Content-Length: '.strlen($jsonStr)
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArr);
// 执行 curl
$ret = curl_exec($ch);
// curl 关闭请求
curl_close();
注:
1,当传参类型为 application/json 时,只能用 file_get_content(‘php://input’) 来接收。
2,$_POST 只能接收传参类型为 application/x-www-form-urlencoded || multipart/from-data 两种类型
本文详细介绍了CURL在PHP中进行GET和POST请求的方法。GET请求主要用于获取资源,而POST请求用于传递数据。在POST请求中,需设置CURLOPT_POST为true,并通过CURLOPT_POSTFIELDS传递JSON字符串。当接收到application/json类型的数据时,应使用file_get_contents('php://input')获取。$_POST仅能处理application/x-www-form-urlencoded或multipart/form-data类型的POST数据。
1153

被折叠的 条评论
为什么被折叠?



