使用 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
        ];
    }

实现一个 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;
        }
    }
    
}
posted @   xingduo  阅读(139)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· spring官宣接入deepseek,真的太香了~
点击右上角即可分享
微信分享提示