本文介绍了在Guzzle中设置代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在设置代理服务器时遇到了一个问题:在卷曲的情况下显示空白页,而一切正常。下面是我在枪口和卷曲中使用的代码。
此代码有什么问题:
枪口:

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 wrong with this code:Guzzle:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

require_once "vendor/autoload.php";

try {
  $client = new Client();
  $request = new \GuzzleHttp\Psr7\Request('GET', 'http://httpbin.org');
  $response = $client->send($request, [
      'timeout'  => 30,
      'curl'  => [
          'CURLOPT_PROXY' => '*.*.*.*',
          'CURLOPT_PROXYPORT' => *,
          'CURLOPT_PROXYUSERPWD' => '*:*',
      ],

  ]);
  echo '</pre>';
  echo($response->getBody());
  exit;
} catch (RequestException $e) {
  echo $e->getRequest();
  if ($e->hasResponse()) {
      echo $e->getResponse();
  }
}

并且带有CURL的代码:

And The code with CURL:

$url = 'http://httpbin.org';
$ch = curl_init($url);
curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
curl_setopt($ch, CURLOPT_PROXY, '*.*.*.*');
curl_setopt($ch, CURLOPT_PROXYPORT, *);
curl_setopt($ch, CURLOPT_PROXYUSERPWD, '*:*');
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$page = curl_exec($ch);
echo $page;

谢谢。

推荐答案

关于 Guzzle 6

提供有关为单个请求设置代理的信息

Guzzle docs give info about setting proxy for a single request

$client->request('GET', '/', ['proxy' => 'tcp://localhost:8125']);

但是您可以在初始化客户端时将其设置为所有请求

But you can set it to all requests when initializing client

    $client = new Client([
        'base_uri' => 'http://doma.in/',
        'timeout' => 10.0,
        'cookie' => true,
        'proxy' => 'tcp://12.34.56.78:3128',
    ]);

UPD。我不知道为什么,但是我面临着奇怪的行为。一台服务器版本为6.2.2的服务器可以很好地与上述配置配合使用,而另一台服务器具有相同版本,则从代理接收到 400错误请求 HTTP错误。通过另一个配置结构(可以在中找到)

UPD. I don't know why, but I face a strange behaviour. One server with guzzle version 6.2.2 works great with config as above, and the other one with the same version receives 400 Bad Request HTTP error from a proxy. It is solved with another config structure (found in docs for guzzle 3)

$client = new Client([
    'base_uri' => 'http://doma.in/',
    'timeout' => 10.0,
    'cookie' => true,
    'request.options' => [
        'proxy' => 'tcp://12.34.56.78:3128',
    ],
]);

这篇关于在Guzzle中设置代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 04:52