我正试图将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...)
但这根本没有代理权。。
任何建议/帮助都将令人惊叹。。
弗拉德。
GuzzleHttpPsr7Request
不像GuzzleHttpClient
那样接受GuzzleHttpRequestOptions
,因此当生成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));