Set proxy in Guzzle

后端 未结 6 481
广开言路
广开言路 2021-01-11 13:06

I have a problem with set proxy in guzzle that a blank page was shown while with curl everything works perfect. The code that I used in guzzle and curl came below. What is w

6条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-11 13:35

    For Guzzle6, I think the best way is to implement a middleware for setting proxy.

    From Guzzle6 docs:

    • request-options.proxy
    • handlers-and-middleware

    We can set proxy as below:

    use Psr\Http\Message\RequestInterface;
    use GuzzleHttp\HandlerStack;
    use GuzzleHttp\Handler\CurlHandler;
    use GuzzleHttp\Client;
    use GuzzleHttp\Middleware;
    use Util\Api;
    function add_proxy_callback($proxy_callback) {
        return function (callable $handler) use ($proxy_callback) {
            return function (RequestInterface $request,$options) use ($handler,$proxy_callback) {
                $ip = $proxy_callback();
                $options['proxy'] = $ip;
                return $handler($request,$options);
            };
        };
    } 
    $stack = new HandlerStack();
    $stack->setHandler(new CurlHandler());
    $stack->push(add_proxy_callback(function() {
        return Api::getIp(); //function return a ip 
    }));
    $client = new Client(['handler'=>$stack]);
    $response = $client->request('GET','http://httpbin.org/ip');
    var_dump((string)$response->getBody());
    

提交回复
热议问题