PHP Guzzle Pool 请求,每个请求都有代理

PHP Guzzle Pool requests with proxy per request

我正在尝试将 Pool 请求设置为多个 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...)

但那根本就没有代理..

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

弗拉德。

GuzzleHttp\Psr7\Request 不像它的 GuzzleHttp\Client 那样接受 GuzzleHttp\RequestOptions 在产生 Request 并传递 'proxy'选项,Request没有效果。

你需要做这样的事情

$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));