使用 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 ...
随机推荐
- JVM实战—11.OOM的原因和模拟以及案例
大纲 1.线上系统突然由于OOM内存溢出挂掉 2.什么是内存溢出及哪些区域会发生内存溢出 3.Metaspace如何因类太多而发生内存溢出 4.无限制调用方法如何让线程的栈内存溢出 5.对象太多导致堆 ...
- Linux下获取文件名
linux 下一切皆文件 1.获取指定路径下文件或目录 ls -la /usr/local/ |grep xxx | head -n 1 |awk '{print$9}'xxx : 替换为要匹配的文件 ...
- 快速上手jquery
优点 强大的选择器机制 优质的隐私迭代 链式编程 选择机制 选择器 标签名 $('div') id $('#id') class $('.clname') 属性 $('div:[name='66']' ...
- ffmpeg实现视频的合成与分割
视频合成与分割程序使用 作者开发了一款软件,可以实现对视频的合成和分割,界面如下: 下载该程序 播放时,可以选择多个视频源:在选中"保存视频"情况下,会将多个视频源合成一个视频 ...
- CDS标准视图:功能位置可用标签 I_FUNCNLLOCALTERNATIVELABEL
视图名称:功能位置可用标签 I_FUNCNLLOCALTERNATIVELABEL 视图类型:基础 视图代码: 点击查看代码 @EndUserText.label: 'Functional Locat ...
- linux-大数据常用命令
1. vi/vim一般模式语法 功能描述yy 复制光标当前一行y数字y 复制一段(从第几行到第几行)p 箭头移动到目的行粘贴u 撤销上一步dd 删除光标当前行d数字d 删除光标(含)后多少行x 删除一 ...
- MYSQL-收集
1.MySQL敏感数据进行加密的几种方法小结 AES_ENCRYPT和AES_DECRYPT函数 AES(Advanced Encryption Standard)是一种对称加密算法.在MySQL中, ...
- atomikos实现分布式事务
date: 2022-04-25 categories: [java, 编程] tags: [分布式事务] 概述 多数据源单服务写入, 分布式事务实现 使用随机数控制产生异常 注: 网上很多都是只有多 ...
- uniapp编译成小程序无法设置背景色
参考地址: https://blog.csdn.net/weixin_42120767/article/details/107550236 在原生微信小程序中,我们可以设置page{backgroun ...
- 爬虫基础知识及scrapy框架使用和基本原理
爬虫 一.异步IO 线程:线程是计算机中工作的最小单元 IO请求(IO密集型)时多线程更好,计算密集型进程并发最好,IO请求不涉及CPU 自定义线程池 进程:进程默认有主线程,可以有多线程共存,并 ...