使用 PHP cURL 实现 HTTP 请求类
类结构
创建一个 HttpRequest 类,其中包括初始化 cURL 的方法、不同类型的 HTTP 请求方法,以及一些用于处理响应头和解析响应内容的辅助方法。
初始化 cURL
首先,创建一个私有方法 initCurl,用于初始化 cURL 句柄并设置一些常用的选项。
class HttpRequest
{
private function initCurl($url, $headers)
{
$ch = curl_init($url);
// 常用选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true); // 包含响应头
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 绕过HTTPS验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return $ch;
}
发送 GET 请求
实现一个 get 方法,发送 GET 请求并返回响应的头部和主体。
public function get($url, $headers = [])
{
$ch = $this->initCurl($url, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, true);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('cURL Error: ' . $error);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
return [
'header' => $header,
'body' => $body
];
}
发送 POST 请求
接下来是 post 方法,用于发送 POST 请求。可以传递数据和可选的头部信息。
public function post($url, $data, $headers = [], $cookies = null)
{
$ch = $this->initCurl($url, $headers);
curl_setopt($ch, CURLOPT_POST, true);
if (is_array($data)) {
$data = http_build_query($data);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('cURL Error: ' . $error);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
return [
'header' => $header,
'body' => $body
];
}
发送 PUT 请求
然后是 put 方法,用于发送 PUT 请求。
public function put($url, $headers = [])
{
$ch = $this->initCurl($url, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('cURL Error: ' . $error);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
return [
'header' => $header,
'body' => $body
];
}
解析 Set-Cookie 头
实现一个 parseSetCookieHeader 方法,用于解析响应头中的 Set-Cookie 头。
public function parseSetCookieHeader($header)
{
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
if (empty($matches[1])) {
return ''; // 没有找到 Set-Cookie 头,返回空字符串
}
$cookieStrings = [];
foreach ($matches[1] as $item) {
$cookieStrings[] = $item;
}
return implode('; ', $cookieStrings);
}
解析响应内容
最后,我们实现一个 parseResponseFormat 方法,根据响应头中的 Content-Type 解析响应内容。
public function parseResponseFormat($header, $body)
{
if (strpos($header, 'Content-Type: application/json') !== false) {
return json_decode($body, true);
} elseif (strpos($header, 'Content-Type: application/xml') !== false || strpos($header, 'Content-Type: text/xml') !== false) {
$xmlObject = simplexml_load_string($body);
if ($xmlObject !== false) {
return json_decode(json_encode($xmlObject));
} else {
return [];
}
} else {
return $body;
}
}
}
点击查看代码
<?php
class HttpRequest
{
private function initCurl($url, $headers)
{
$ch = curl_init($url);
// 常用选项
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true); // 包含响应头
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 绕过HTTPS验证
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
return $ch;
}
public function put($url, $headers = [])
{
$ch = $this->initCurl($url, $headers);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
// curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('cURL Error: ' . $error);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
return [
'header' => $header,
'body' => $body
];
}
public function get($url, $headers = [])
{
$ch = $this->initCurl($url, $headers);
curl_setopt($ch, CURLOPT_HTTPGET, true);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('cURL Error: ' . $error);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
return [
'header' => $header,
'body' => $body
];
}
public function post($url, $data, $headers = [], $cookies = null)
{
$ch = $this->initCurl($url, $headers, $cookies);
curl_setopt($ch, CURLOPT_POST, true);
if(is_array($data)){
$data = http_build_query($data);
}
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($ch);
if ($response === false) {
$error = curl_error($ch);
curl_close($ch);
throw new Exception('cURL Error: ' . $error);
}
$headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $headerSize);
$body = substr($response, $headerSize);
curl_close($ch);
return [
'header' => $header,
'body' => $body
];
}
public function parseSetCookieHeader($header)
{
preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
if (empty($matches[1])) {
return ''; // 没有找到 Set-Cookie 头,返回空字符串
}
$cookieStrings = [];
foreach ($matches[1] as $item) {
$cookieStrings[] = $item;
}
return implode('; ', $cookieStrings);
// preg_match_all('/^Set-Cookie:\s*([^;]*)/mi', $header, $matches);
// $cookies = [];
// foreach ($matches[1] as $item) {
// parse_str($item, $cookie);
// $cookies = array_merge($cookies, $cookie);
// }
// return $cookies;
}
public function parseResponseFormat($header, $body)
{
if (strpos($header, 'Content-Type: application/json') !== false) {
return json_decode($body, true);
} elseif (strpos($header, 'Content-Type: application/xml') !== false || strpos($header, 'Content-Type: text/xml') !== false) {
$xmlObject = simplexml_load_string($body);
if ($xmlObject !== false) {
return json_decode(json_encode($xmlObject));
} else {
return [];
}
} else {
return $body;
}
}
}
使用 PHP cURL 实现 HTTP 请求类的更多相关文章
- laravel各种请求类
curl请求类 composer require php-curl-class/php-curl-class
- 使用curl进行https请求
简单示例: /** * @param $url * @return array * 进行https请求,并且遇到location进行跳转 */ function https($url){ $resul ...
- http 请求类
1.httpclient请求类 代理demo:http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apac ...
- PHP CURL 多线程 GET/POST 类
PHP CURL 多线程 GET/POST 类 2015-01-01 分类:技术文章 阅读(623) 评论(0) 如果有需要更正或更高效的建议,欢迎在OSchina分享~\(≧▽≦)/~ http:/ ...
- curl获取http请求的状态码
$curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $url); //设置头文件的信息作为数据流输出 curl_setopt($curl, CUR ...
- php curl模拟post请求提交数据样例总结
在php中要模拟post请求数据提交我们会使用到curl函数,以下我来给大家举几个curl模拟post请求提交数据样例有须要的朋友可參考參考.注意:curl函数在php中默认是不被支持的,假设须要使用 ...
- php 使用curl发起https请求
今天一个同事反映,使用curl发起https请求的时候报错:“SSL certificate problem, verify that the CA cert is OK. Details: erro ...
- 老李分享:curl发起https请求
老李分享:curl发起https请求 在POPTEST上课的过程中,我们需要本地模拟https请求来完成性能测试,我们用curl来实现,curl是利用URL语法在命令行方式下工作的开源文件传输工具,使 ...
- thinkphp5 Request请求类
获取请求类的几种方式: 1.助手函数(严格不算ba ) input('post.name'): 2.$request=\think\Request::instance(); 3.控制器中必须继承Con ...
- WorldWind源码剖析系列:下载请求类DownloadRequest
下载请求类DownloadRequest是各种下载请求的抽象基类,先派生出网络下载请求类WebDownloadRequest,再派生出地理空间下载请求类GeoSpatialDownloadReques ...
随机推荐
- 优化博客Ⅰ-压缩图片为webp格式
自动压缩博客图片为webp格式 作为自己的个人博客,我非常喜欢搞一些花里胡哨的东西,其中就包括不少精美图片,但是过多的图片会占用大量的网络资源导致博客加载速度变慢. 那怎么办呢? 第一个想到的就是升级 ...
- Note - 两类容斥
\(\S1.\) 等价容斥 (乱取的名字.) 题目将组合对象构成的 "等价类" 进行了定义和限定. 我们往往无法计数 "等价类真的长这样" 的方案, 而 ...
- CDS标准视图:功能位置可用标签 I_FUNCNLLOCALTERNATIVELABEL
视图名称:功能位置可用标签 I_FUNCNLLOCALTERNATIVELABEL 视图类型:基础 视图代码: 点击查看代码 @EndUserText.label: 'Functional Locat ...
- Win2D 投影效果 ShadowEffect
<Page x:Class="Win2DDemo.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/ ...
- C 2017笔试题
1.下面程序的输出结果是 int x=3; do { printf("%d\n",x-=2); }while(!(--x)); 输出:1 -2 解析:x初始值为3,第一次循环中运行 ...
- DCT实现水印嵌入与提取(带攻击)
问题: 想要用DCT技术,在Matlib上实现水印的隐藏和提取(带GUI界面),且加上一些攻击(噪声.旋转.裁剪),以及用NC值评判! 流程 选择载体 [filename,pathname]=uige ...
- H5调用手机拨打电话的功能
里面加上: 我没有写也是可以的 <meta name="format-detection" content="telephone=yes"/> 该标 ...
- Python 数
Python 数 在Python中,数字是编程中不可或缺的一部分.Python支持多种类型的数字,包括整数.浮点数等.下面我们将详细介绍这些数字类型以及它们之间的运算和格式化. 整数 整数是Pytho ...
- nacos(四): 创建第一个消费者Conumer(单体)
接上一篇<nacos(三): 创建第一个生产者producer(单体)>,我们这一篇实现单体的消费者功能,准备与上一次的生产者集成在一个单体项目中. 消费者的本质其实就是向nacos注册后 ...
- 安川机器人U轴减速机 HW9381465-C维修具体细节
安川机器人U轴减速机 HW9381465-C的维修是一个相对复杂的过程,涉及到多个部件的检查.维修和更换.以下是一些具体细节: 1.故障诊断: · 对安川机器人U轴减速机 HW9381465-C进行彻 ...