封装简便请求类

浮梦 153 2024-04-11

python代码

import requests

class AutoReferrerSession(requests.Session):
    def request(self, method, url, **kwargs):
        headers = kwargs.setdefault('headers', {})
        # 如果请求历史为空,则设置Referer为当前请求的URL
        if not self.history:
            headers['Referer'] = url
        else:
            # 对于非首次请求,从历史记录中获取Referer
            previous_url = self.history[-1] if self.history else None
            headers['Referer'] = previous_url

        self.history.append(url)
        return super().request(method, url, **kwargs)

    # 对常用的HTTP方法进行装饰,它们都会自动调用request方法
    def get(self, url, **kwargs):
        return self.request('GET', url, **kwargs)

    def post(self, url, data=None, json=None, **kwargs):
        return self.request('POST', url, data=data, json=json, **kwargs)

    def put(self, url, data=None, **kwargs):
        return self.request('PUT', url, data=data, **kwargs)

    def delete(self, url, **kwargs):
        return self.request('DELETE', url, **kwargs)

# 使用自定义的AutoReferrerSession
session = AutoReferrerSession()
response1 = session.get('http://first-url.com')  # 首次请求,Referer为请求的URL自身
response2 = session.get('http://second-url.com')  # 此后请求,Referer为上一次请求的URL

PHP代码

<?php
class AutoReferrerCurlClient
{
    private $history = [];
    
    public function request($method, $url, $initial_referer = null)
    {
        // 初始化cURL资源
        $ch = curl_init();

        // 设置URL和HTTP方法
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, strtoupper($method));

        // 设置Referer头
        $referer = $initial_referer ?? ($this->history ? end($this->history) : '');
        if (!empty($referer)) {
            curl_setopt($ch, CURLOPT_REFERER, $referer);
        }

        // 执行请求并将响应内容存储起来
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);

        // 将本次请求的URL添加到历史记录中
        $this->history[] = $url;

        // 获取HTTP状态码
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        // 关闭cURL资源
        curl_close($ch);

        // 返回响应内容和HTTP状态码
        return [
            'content' => $response,
            'status_code' => $http_status,
        ];
    }

    // 实现常用的HTTP方法
    public function get($url, $initial_referer = null)
    {
        return $this->request('GET', $url, $initial_referer);
    }

    public function post($url, $data = [], $initial_referer = null)
    {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        return $this->request('POST', $url, $initial_referer);
    }

    // PUT和DELETE方法同样可以通过修改request方法内部逻辑实现
    // 这里仅展示POST方法,PUT和DELETE可以仿照POST方法添加curl_setopt设置
    // ...

    // 示例使用:
    $client = new AutoReferrerCurlClient();
    $response1 = $client->get('http://first-url.com', 'http://starting-referer.com');
    $response2 = $client->get('http://second-url.com');  // 此时Referer会自动设置为上一个请求的URL
}

// 使用示例:
$client = new AutoReferrerCurlClient();
$response = $client->get('http://first-url.com', 'http://starting-referer.com');

// 解析响应内容
$content = $response['content'];
$status_code = $response['status_code'];