使用 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 ...
随机推荐
- Next.js + Mongodb CURD
环境 Next.js 14 React 18 Mongodb 前言 花了两周时间学习了Next.js, 自己做了个demo,尝试了下服务器端渲染,客户端渲染,给人的感觉就是又像回到了asp.net M ...
- # 个人认为windows下最好用的一批软件 #
个人认为windows下最好用的一批软件 chrome 为什么是chrome而不是edge2? 这当然不是因为我是谷歌吹什么的.其实当得知edge2比chrome更省内存,运行更快,而且不跨越城墙就能 ...
- uni-app如何只用插件市场中的插件
将你需要的插件下载下来.比如说如下图 在pages.json配置 globalStyle是一个单独的字段 "globalStyle": { "usingComponent ...
- WAIC 2024盛大召开,天翼云以全栈智算能力赋能AI时代!
7月5日,2024世界人工智能大会期间,中国电信星辰人工智能生态论坛在上海世博中心启幕.论坛以"星辰注智,焕新领航"为主题,围绕人工智能技术发展趋势,分享中国电信与产业各界在人工智 ...
- VsCode 配置python开发环境
一.配置环境 1.选择python解释器版本 输入:Command+shift+P 搜索:Python: Select Interpreter 2.安装包 指定版本: pip install PyHi ...
- Luogu P2540 NOIP2015提高组 斗地主 加强版 题解 [ 紫 ] [ 深搜 ] [ 剪枝 ]
斗地主:一步一步推性质就能做出来的剪枝题. 这题思路和小木棒的剪枝思路极其相似,剪枝的角度都差不多. 其实大部分搜索剪枝题都是先观察性质,列出性质后选择几个比较关键且代码好写的性质进行剪枝,特别要注意 ...
- 一文详解 MySQL 中的间隙锁
博客:https://www.emanjusaka.com 博客园:https://www.cnblogs.com/emanjusaka 公众号:emanjusaka的编程栈 by emanjusak ...
- datawhale-leetcode打卡:第026~037题
反转链表(leetcode 206) 这个题目我就比较流氓了,干脆新建链表翻转过来算了.但是完蛋,超出内存限制,那我就只能两两换了.这里比较大的技巧就是可以用一个空节点进行置换. # Definiti ...
- 数据团队必读:智能数据分析文档(DataV Note)五种高效工作模式
数据项目,无论是数据分析.可视化,还是数据科学和机器学习相关的项目,通常都非常复杂,涉及多个组成部分,比如代码.数据.运行环境.SQL脚本以及分析报告等:与此同时,随着AI时代的到来,数据科学领域正经 ...
- STM32 DMA操作
https://blog.csdn.net/u014754841/article/details/79525637?utm_medium=distribute.pc_relevant.none-tas ...