2017-05-31 94 views
0

連接到網站與未知的方案我有沒有指定的方案URL列表,例:通過狂飲

  • github.com(僅適用於https);
  • what.ever(只適用於http);
  • google.com(支持兩種方案)。

我需要使用狂飲(V6)的根路徑(/)的內容,但我不知道他們的計劃:httphttps

我可以解決我的任務而不發出2個請求嗎?

+0

只有當網站自動重定向您並且您將Guzzle配置爲遵循重定向。 –

回答

0

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 
0

一般 - 不,你不能沒有兩個請求解決問題(因爲一個有可能是沒有重定向)。

你可以用Guzzle做2個異步請求,那麼你可能會花費同一時間,但有一個適當的通用解決方案。

只需創建兩個請求,並等待兩個:

$httpResponsePromise = $client->getAsync('http://' . $url); 
$httpsResponsePromise = $client->getAsync('https://' . $url); 

list($httpResponse, $httpsResponse) = \GuzzleHttp\Promise\all(
    [$httpResponsePromise, $httpsResponsePromise] 
); 

這一切,現在你有(每個協議)兩種反應,你讓他們並行。