使用 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 ...
随机推荐
- NVIDIA-SMI打印信息解析
- Java常用的并发类-总结列表
一.java集合框架概述 java集合可分为Collection和Map两种体系,其中: 1.Collection接口:单列数据,定义了存取一组对象的方法的集合: List:元素有序.可重复的集合 S ...
- w3cschool-Apache Storm 教程
https://www.w3cschool.cn/apache_storm/ Apache Storm教程Apache Storm简介Apache Storm核心概念Apache Storm集群架构A ...
- biancheng-Spring Cloud Alibaba Sentinel
http://c.biancheng.net/springcloud/sentinel.html Sentinel 是由阿里巴巴中间件团队开发的开源项目,是一种面向分布式微服务架构的轻量级高可用流量控 ...
- Java多进程多线程处理详解
在Java编程中,多进程和多线程是两种常见的并发编程技术,用于提高程序的执行效率和响应速度.本文将详细介绍Java中的多进程和多线程处理,包括理论概述和代码示例.通过本文,你将了解如何在Java中实现 ...
- 【推荐】一款开源且成熟的OA协同办公系统,自带低代码开发功能!
项目介绍 今天给大家推荐一款开源且拥有成熟的OA办公系统功能,自带低代码开发平台,可以快速搭建OA系统.人事系统.CRM系统.办公用品系统.项目管理系统.合同管理系统等,让你可以快速上手.快速实施.快 ...
- 从生活案例理解滑动窗口最大值:一个超直观的思路讲解|LeetCode 239 滑动窗口最大值
LeetCode 239 滑动窗口最大值 点此看全部题解 LeetCode必刷100题:一份来自面试官的算法地图(题解持续更新中) 更多干货,请关注公众号[忍者算法],回复[刷题清单]获取完整题解目录 ...
- Q:ssh远程连接慢的原因排查
连接linux服务器一般都是使用SSH远程连接的方式.有时,SSH连接速度很慢,大约30s左右,但是ping时一切正常. 问题原因 1.server的sshd会去DNS查找访问的client ip的h ...
- Linux下普通用户免密切换root
问题需求: Linux下普通用户doge免密切换root 问题解决: Linux下普通用户切换到root用户下,默认情况是需要输入密码很不方便,因此需要实现普通用户doge免密切换到root用户. 示 ...
- FLink17--聚合函数-AggWindowApp
一.依赖 二.代码 package net.xdclass.class11; import org.apache.flink.api.common.RuntimeExecutionMode; impo ...