【问题标题】:Connect to site with unknown scheme via Guzzle通过 Guzzle 连接到未知方案的站点
【发布时间】:2017-11-01 12:26:25
【问题描述】:

我有一个没有指定方案的 URL 列表,例如:

  • github.com(仅适用于https);
  • what.ever(仅适用于 http);
  • google.com(支持这两种方案)。

我需要使用 Guzzle (v6) 获取其根路径 (/) 的内容,但我不知道他们的方案:httphttps

我可以在不发出 2 个请求的情况下解决我的任务吗?

【问题讨论】:

  • 仅当网站自动重定向您并且您将 Guzzle 配置为遵循重定向时。

标签: php curl guzzle6 guzzle


【解决方案1】:

默认情况下,Guzzle 将遵循重定向,因此除非您有明确的 https 网址列表,否则如果缺少 http,我将在前面添加 http,如果网站只接受 https 请求(这是他们应该做的),则允许网站重定向。

<?php

require 'vendor/autoload.php';

use GuzzleHttp\Client;

$response = (new Client)->get('http://github.com/', ['debug' => true]);

回复:

> GET / HTTP/1.1
Host: github.com
User-Agent: GuzzleHttp/6.2.1 curl/7.51.0 PHP/5.6.30

< HTTP/1.1 301 Moved Permanently
< Content-length: 0
< Location: https://github.com/
< Connection: close
<
* Curl_http_done: called premature == 0
* Closing connection 0
*   Trying 192.30.253.112...
* TCP_NODELAY set
* Connected to github.com (192.30.253.112) port 443 (#1)
* TLS 1.2 connection using TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
* Server certificate: github.com
* Server certificate: DigiCert SHA2 Extended Validation Server CA
* Server certificate: DigiCert High Assurance EV Root CA
> GET / HTTP/1.1
Host: github.com
User-Agent: GuzzleHttp/6.2.1 curl/7.51.0 PHP/5.6.30

< HTTP/1.1 200 OK
< Server: GitHub.com
< Date: Wed, 31 May 2017 15:46:59 GMT
< Content-Type: text/html; charset=utf-8
< Transfer-Encoding: chunked
< Status: 200 OK

【讨论】:

    【解决方案2】:

    通常——不,如果没有两个请求,您将无法解决问题(因为一个可能没有重定向)。

    您可以使用 Guzzle 执行 2 个异步请求,然后您可能会花费相同的时间,但需要一个适当的通用解决方案。

    只需创建两个请求并等待两者:

     $httpResponsePromise = $client->getAsync('http://' . $url);
     $httpsResponsePromise = $client->getAsync('https://' . $url);
    
     list($httpResponse, $httpsResponse) = \GuzzleHttp\Promise\all(
         [$httpResponsePromise, $httpsResponsePromise]
     );
    

    就是这样,现在您有两个响应(针对每个协议),并且您可以并行处理它们。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-15
      • 2014-04-11
      • 1970-01-01
      • 2022-01-20
      相关资源
      最近更新 更多