【问题标题】:PHP Guzzle Pool requests with proxy per request每个请求带有代理的 PHP Guzzle Pool 请求
【发布时间】:2021-05-11 17:16:29
【问题描述】:

我正在尝试将池请求设置为多个 url,我唯一的问题是我想在每个请求中设置一个新代理,无法找到正确的方法,尝试使用 Guzzle 文档但没有运气。

我的代码:

$proxies = file('./proxies.txt');
$proxy = trim($proxies[array_rand($proxies)]);

$this->headers['Content-Type'] = 'application/json';
$this->headers['User-Agent'] = 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36';

$client = new Client();

$requests = function(array $data) {
    foreach ($data as $u) {
        yield new Request('POST', $u->url, $this->headers,
            json_encode([
                'text' => $u->s,
            ])
        );

    }
};

$pool = new Pool($client, $requests($data), [
    'concurrency' => 20,
    'fulfilled' => function(Response $response, $index) use ($data) {
        $data->result = json_decode((String)$response->getBody());
        $data->status = True;
        $data->index = $index;
    },
    'rejected' => function(RequestException $reason, $index) use ($data) {
        $data[$index]->index = $index;
        $data[$index]->rejected = $reason;
    }
]);

$promise = $pool->promise();
$promise->wait();

return $data;

代码运行完美,唯一缺少的部分是每次请求都会更改代理。

我试着设置

yield new Request('POST', $u->url, ['proxy' => $proxy], data...)

但这根本就没有代理..

任何建议/帮助都会很棒..

弗拉德。

【问题讨论】:

    标签: php asynchronous proxy python-requests guzzle


    【解决方案1】:

    GuzzleHttp\Psr7\Request 不像 GuzzleHttp\Client 那样采用 GuzzleHttp\RequestOptions,因此当产生 Request 并将 'proxy' 选项传递给它时,请求无效。

    你需要做这样的事情

    $requests = function ($data) use ($client, $proxy, $headers) {
        foreach ($data as $u) {
            yield function() use ($client, $u, $proxy, $headers) {
                return $client->request(
                    'POST',
                    $u->url,
                    [
                        'proxy' => $proxy,
                        'headers' => $headers
                    ]
                );
            };
        }
    };
    
    $pool = new Pool($client, $requests($data));
    

    【讨论】:

      猜你喜欢
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 2018-03-24
      相关资源
      最近更新 更多