zoukankan      html  css  js  c++  java
  • php 请求库 guzzle 的使用

    Guzzle是一个PHP的HTTP客户端,用来轻而易举地发送请求,并集成到我们的WEB服务上。

    • 接口简单:构建查询语句、POST请求、分流上传下载大文件、使用HTTP cookies、上传JSON数据等等。
    • 发送同步或异步的请求均使用相同的接口。
    • 使用PSR-7接口来请求、响应、分流,允许你使用其他兼容的PSR-7类库与Guzzle共同开发。
    • 抽象了底层的HTTP传输,允许你改变环境以及其他的代码,如:对cURL与PHP的流或socket并非重度依赖,非阻塞事件循环。
    • 中间件系统允许你创建构成客户端行为

    官方文档:https://guzzle-cn.readthedocs.io/zh_CN/latest/

    github:https://github.com/guzzle/guzzle

    环境要求

    1. PHP 5.5.0
    2. 使用PHP的流, allow_url_fopen 必须在php.ini中启用。
    3. 要使用cURL,你必须已经有版本cURL >= 7.19.4,并且编译了OpenSSL 与 zlib。

    如果没有安装cURL,Guzzle处理HTTP请求的时候不再使用cURL,而是使用PHP流处理,或者你也可以提供自己的发送HTTP请求的处理方式。

    安装

    composer require guzzlehttp/guzzle:~6.0
    

    该页面提供了Guzzle的快速入门以及列子,如果你还没有安装Guzzle请前往 安装 页面。

    发送请求

    你可以使用Guzzle的 GuzzleHttpClientInterface 对象来发送请求。

    创建客户端

    use GuzzleHttpClient;
    
    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'http://httpbin.org',
        // You can set any number of default request options.
        'timeout'  => 2.0,
    ]);
    

    Client对象可以接收一个包含参数的数组:

    • base_uri

      (string|UriInterface) 基URI用来合并到相关URI,可以是一个字符串或者UriInterface的实例,当提供了相关uri,将合并到基URI,遵循的规则请参考 RFC 3986, section 2 章节。

      // Create a client with a base URI 
      $client = new GuzzleHttpClient(['base_uri' => 'https://foo.com/api/']); 
      // Send a request to https://foo.com/api/test 
      $response = $client->request('GET', 'test'); 
      // Send a request to https://foo.com/root 
      $response = $client->request('GET', '/root');
      

      不想阅读RFC 3986?这里有一些关于 base_uri 与其他URI处理器的快速例子:

      http://foo.com``/bar``
      http://foo.com/bar``
      http://foo.com/foo``/bar``
      http://foo.com/bar``
      http://foo.com/foo``bar``
      http://foo.com/bar``
      http://foo.com/foo/``bar``
      http://foo.com/foo/bar``
      http://foo.com``
      http://baz.com``http://baz.com``
      http://foo.com/?bar``bar``
      http://foo.com/bar
      
    • handler

      传输HTTP请求的(回调)函数。 该函数被调用的时候包含 Psr7HttpMessageRequestInterface 以及参数数组,必须返回 GuzzleHttpPromisePromiseInterface ,成功时满足 Psr7HttpMessageResponseInterfacehandler 是一个构造方法,不能在请求参数里被重写。

    • ...

      (混合) 构造方法中传入的其他所有参数用来当作每次请求的默认参数。

    发送请求

    Client对象的方法可以很容易的发送请求:

    $response = $client->get('http://httpbin.org/get');
    $response = $client->delete('http://httpbin.org/delete');
    $response = $client->head('http://httpbin.org/get');
    $response = $client->options('http://httpbin.org/get');
    $response = $client->patch('http://httpbin.org/patch');
    $response = $client->post('http://httpbin.org/post');
    $response = $client->put('http://httpbin.org/put');
    

    你可以创建一个请求,一切就绪后将请求传送给client:

    use GuzzleHttpPsr7Request;
    
    $request = new Request('PUT', 'http://httpbin.org/put');
    $response = $client->send($request, ['timeout' => 2]);
    

    Client对象为传输请求提供了非常灵活的处理器方式,包括请求参数、每次请求使用的中间件以及传送多个相关请求的基URI。

    你可以在 Handlers and Middleware 页面找到更多关于中间件的内容。

    异步请求

    你可以使用Client提供的方法来创建异步请求:

    $promise = $client->getAsync('http://httpbin.org/get');
    $promise = $client->deleteAsync('http://httpbin.org/delete');
    $promise = $client->headAsync('http://httpbin.org/get');
    $promise = $client->optionsAsync('http://httpbin.org/get');
    $promise = $client->patchAsync('http://httpbin.org/patch');
    $promise = $client->postAsync('http://httpbin.org/post');
    $promise = $client->putAsync('http://httpbin.org/put');
    

    你也可以使用Client的 sendAsync() and requestAsync() 方法:

    use GuzzleHttpPsr7Request;
    
    // Create a PSR-7 request object to send
    $headers = ['X-Foo' => 'Bar'];
    $body = 'Hello!';
    $request = new Request('HEAD', 'http://httpbin.org/head', $headers, $body);
    
    // Or, if you don't need to pass in a request instance:
    $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
    

    这些方法返回了Promise对象,该对象实现了由 Guzzle promises library 提供的 Promises/A+ spec ,这意味着你可以使用 then() 来调用返回值,成功使用 PsrHttpMessageResponseInterface 处理器,否则抛出一个异常。

    use PsrHttpMessageResponseInterface;
    use GuzzleHttpExceptionRequestException;
    
    $promise = $client->requestAsync('GET', 'http://httpbin.org/get');
    $promise->then(
        function (ResponseInterface $res) {
            echo $res->getStatusCode() . "
    ";
        },
        function (RequestException $e) {
            echo $e->getMessage() . "
    ";
            echo $e->getRequest()->getMethod();
        }
    );
    

    并发请求

    你可以使用Promise和异步请求来同时发送多个请求:

    use GuzzleHttpClient;
    use GuzzleHttpPromise;
    
    $client = new Client(['base_uri' => 'http://httpbin.org/']);
    
    // Initiate each request but do not block
    $promises = [
        'image' => $client->getAsync('/image'),
        'png'   => $client->getAsync('/image/png'),
        'jpeg'  => $client->getAsync('/image/jpeg'),
        'webp'  => $client->getAsync('/image/webp')
    ];
    
    // Wait on all of the requests to complete.
    $results = Promiseunwrap($promises);
    
    // You can access each result using the key provided to the unwrap
    // function.
    echo $results['image']->getHeader('Content-Length');
    echo $results['png']->getHeader('Content-Length');
    

    当你想发送不确定数量的请求时,可以使用 GuzzleHttpPool 对象:

    use GuzzleHttpPool;
    use GuzzleHttpClient;
    use GuzzleHttpPsr7Request;
    
    $client = new Client();
    
    $requests = function ($total) {
        $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
        for ($i = 0; $i < $total; $i++) {
            yield new Request('GET', $uri);
        }
    };
    
    $pool = new Pool($client, $requests(100), [
        'concurrency' => 5,
        'fulfilled' => function ($response, $index) {
            // this is delivered each successful response
        },
        'rejected' => function ($reason, $index) {
            // this is delivered each failed request
        },
    ]);
    
    // Initiate the transfers and create a promise
    $promise = $pool->promise();
    
    // Force the pool of requests to complete.
    $promise->wait();
    

    使用响应

    前面的例子里,我们取到了 $response 变量,或者从Promise得到了响应,Response对象实现了一个PSR-7接口 PsrHttpMessageResponseInterface , 包含了很多有用的信息。

    你可以获取这个响应的状态码和和原因短语(reason phrase):

    $code = $response->getStatusCode(); // 200
    $reason = $response->getReasonPhrase(); // OK
    

    你可以从响应获取头信息(header):

    // Check if a header exists.
    if ($response->hasHeader('Content-Length')) {
        echo "It exists";
    }
    
    // Get a header from the response.
    echo $response->getHeader('Content-Length');
    
    // Get all of the response headers.
    foreach ($response->getHeaders() as $name => $values) {
        echo $name . ': ' . implode(', ', $values) . "
    ";
    }
    

    使用 getBody 方法可以获取响应的主体部分(body),主体可以当成一个字符串或流对象使用

    $body = $response->getBody();
    // Implicitly cast the body to a string and echo it
    echo $body;
    // Explicitly cast the body to a string
    $stringBody = (string) $body;
    // Read 10 bytes from the body
    $tenBytes = $body->read(10);
    // Read the remaining contents of the body as a string
    $remainingBytes = $body->getContents();
    

    查询字符串参数

    你可以有多种方式来提供请求的查询字符串 你可以在请求的URI中设置查询字符串:

    $response = $client->request('GET', 'http://httpbin.org?foo=bar');
    

    你可以使用 query 请求参数来声明查询字符串参数:

    $client->request('GET', 'http://httpbin.org', [
        'query' => ['foo' => 'bar']
    ]);
    

    提供的数组参数将会使用PHP的 http_build_query

    最后,你可以提供一个字符串作为 query 请求参数:

    $client->request('GET', 'http://httpbin.org', ['query' => 'foo=bar']);
    

    上传数据

    Guzzle为上传数据提供了一些方法。 你可以发送一个包含数据流的请求,将 body 请求参数设置成一个字符串、 fopen 返回的资源、或者一个 PsrHttpMessageStreamInterface 的实例。

    // Provide the body as a string.
    $r = $client->request('POST', 'http://httpbin.org/post', [
        'body' => 'raw data'
    ]);
    
    // Provide an fopen resource.
    $body = fopen('/path/to/file', 'r');
    $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
    
    // Use the stream_for() function to create a PSR-7 stream.
    $body = GuzzleHttpPsr7stream_for('hello!');
    $r = $client->request('POST', 'http://httpbin.org/post', ['body' => $body]);
    

    上传JSON数据以及设置合适的头信息可以使用 json 请求参数这个简单的方式:

    $r = $client->request('PUT', 'http://httpbin.org/put', [
        'json' => ['foo' => 'bar']
    ]);
    

    POST/表单请求

    除了使用 body 参数来指定请求数据外,Guzzle为发送POST数据提供了有用的方法。

    发送表单字段

    发送 application/x-www-form-urlencoded POST请求需要你传入 form_params 数组参数,数组内指定POST的字段。

    $response = $client->request('POST', 'http://httpbin.org/post', [
        'form_params' => [
            'field_name' => 'abc',
            'other_field' => '123',
            'nested_field' => [
                'nested' => 'hello'
            ]
        ]
    ]);
    

    发送表单文件

    你可以通过使用 multipart 请求参数来发送表单(表单enctype属性需要设置 multipart/form-data )文件, 该参数接收一个包含多个关联数组的数组,每个关联数组包含一下键名:

    • name: (必须,字符串) 映射到表单字段的名称。
    • contents: (必须,混合) 提供一个字符串,可以是 fopen 返回的资源、或者一个

    PsrHttpMessageStreamInterface 的实例。

    $response = $client->request('POST', 'http://httpbin.org/post', [
        'multipart' => [
            [
                'name'     => 'field_name',
                'contents' => 'abc'
            ],
            [
                'name'     => 'file_name',
                'contents' => fopen('/path/to/file', 'r')
            ],
            [
                'name'     => 'other_file',
                'contents' => 'hello',
                'filename' => 'filename.txt',
                'headers'  => [
                    'X-Foo' => 'this is an extra header to include'
                ]
            ]
        ]
    ]);
    

    Cookies

    Guzzle可以使用 cookies 请求参数为你维护一个cookie会话,当发送一个请求时, cookies 选项必须设置成 GuzzleHttpCookieCookieJarInterface 的实例。

    // Use a specific cookie jar
    $jar = new GuzzleHttpCookieCookieJar;
    $r = $client->request('GET', 'http://httpbin.org/cookies', [
        'cookies' => $jar
    ]);
    

    You can set cookies to true in a client constructor if you would like to use a shared cookie jar for all requests.

    // Use a shared client cookie jar
    $client = new GuzzleHttpClient(['cookies' => true]);
    $r = $client->request('GET', 'http://httpbin.org/cookies');
    

    重定向

    如果你没有告诉Guzzle不要重定向,Guzzle会自动的进行重定向,你可以使用 allow_redirects 请求参数来自定义重定向行为。

    • 设置成 true 时将启用最大数量为5的重定向,这是默认设置。
    • 设置成 false 来禁用重定向。
    • 传入一个包含 max 键名的关联数组来声明最大重定向次数,提供可选的 strict 键名来声明是否使用严格的RFC标准重定向 (表示使用POST请求重定向POST请求 vs 大部分浏览器使用GET请求重定向POST请求)。
    $response = $client->request('GET', 'http://github.com');
    echo $response->getStatusCode();
    // 200
    

    下面的列子表示重定向被禁止:

    $response = $client->request('GET', 'http://github.com', [
        'allow_redirects' => false
    ]);
    echo $response->getStatusCode();
    // 301
    

    异常

    请求传输过程中出现的错误Guzzle将会抛出异常。

    • 在发送网络错误(连接超时、DNS错误等)时,将会抛出 GuzzleHttpExceptionRequestException 异常。 该异常继承自 GuzzleHttpExceptionTransferException ,捕获这个异常可以在传输请求过程中抛出异常。

      use GuzzleHttpExceptionRequestException;
      
      try {
          $client->request('GET', 'https://github.com/_abc_123_404');
      } catch (RequestException $e) {
          echo $e->getRequest();
          if ($e->hasResponse()) {
              echo $e->getResponse();
          }
      }
      
    • GuzzleHttpExceptionConnectException 异常发生在网络错误时, 该异常继承自 GuzzleHttpExceptionRequestException

    • 如果 http_errors 请求参数设置成true,在400级别的错误的时候将会抛出 GuzzleHttpExceptionClientException 异常, 该异常继承自 GuzzleHttpExceptionBadResponseException GuzzleHttpExceptionBadResponseException 继承自 GuzzleHttpExceptionRequestException

      use GuzzleHttpExceptionClientException;
      
      try {
          $client->request('GET', 'https://github.com/_abc_123_404');
      } catch (ClientException $e) {
          echo $e->getRequest();
          echo $e->getResponse();
      }
      
    • 如果 http_errors 请求参数设置成true,在500级别的错误的时候将会抛出 GuzzleHttpExceptionServerException 异常。 该异常继承自 GuzzleHttpExceptionBadResponseException

    • GuzzleHttpExceptionTooManyRedirectsException 异常发生在重定向次数过多时, 该异常继承自 GuzzleHttpExceptionRequestException

    上述所有异常均继承自 GuzzleHttpExceptionTransferException

    环境变量

    Guzzle提供了一些可自定义的环境变量:

    • GUZZLE_CURL_SELECT_TIMEOUT

      当在curl处理器时使用 curl_multi_select() 控制了 curl_multi_* 需要使用到的持续时间, 有些系统实现PHP的 curl_multi_select() 存在问题,调用该函数时总是等待超时的最大值。

    • HTTP_PROXY

      定义了使用http协议发送请求时使用的代理。

    • HTTPS_PROXY

      定义了使用https协议发送请求时使用的代理。

    相关ini设置

    Guzzle配置客户端时可以利用PHP的ini配置。

    请求选项

    你可以通过设置Client的 请求选项 来自定义请求,请求参数控制请求的各个方面,包括头信息、查询字符串参数、超时、请求主体等。

    下述所有的列子都使用下面的Client:

    $client = new GuzzleHttpClient(['base_uri' => 'http://httpbin.org']);
    

    allow_redirects

    • 摘要

      描述请求的重定向行为

    • 类型

      boolarray

    • 默认值

      [
          'max'             => 5,
          'strict'          => false,
          'referer'         => true,
          'protocols'       => ['http', 'https'],
          'track_redirects' => false
      ]
      
    • 常量

      GuzzleHttpRequestOptions::ALLOW_REDIRECTS

    设置成 false 禁用重定向。

    $res = $client->request('GET', '/redirect/3', ['allow_redirects' => false]);
    echo $res->getStatusCode();
    // 302
    

    设置成 true (默认设置) 来启用默认最大次数为5的重定向。

    $res = $client->request('GET', '/redirect/3');
    echo $res->getStatusCode();
    // 200
    

    你也可以传送一个包含了以下键值对的关联数组:

    • max: (int, 默认为5) 允许重定向次数的最大值。
    • strict: (bool, 默认为false) 设置成 true 使用严格模式重定向 严格RFC模式重定向表示使用POST请求重定向POST请求 vs 大部分浏览器使用GET请求重定向POST请求。
    • referer: (bool, 默认为true) 设置成 false 重定向时禁止添加Refer头信息。
    • protocols: (array, 默认为['http', 'https']) 指定允许重定向的协议。
    • on_redirect: (callable) 发生重定向时调用PHP回调,包含了原始的请求以及接收到重定向的响应,on_redirect的任何返回将会被忽略。
    • track_redirects: (bool) 当设置成 true 时,每个重定向的URI将会按序被跟踪头信息 X-Guzzle-Redirect-History
    use PsrHttpMessageRequestInterface;
    use PsrHttpMessageResponseInterface;
    use PsrHttpMessageUriInterface;
    
    $onRedirect = function(
        RequestInterface $request,
        ResponseInterface $response,
        UriInterface $uri
    ) {
        echo 'Redirecting! ' . $request->getUri() . ' to ' . $uri . "
    ";
    };
    
    $res = $client->request('GET', '/redirect/3', [
        'allow_redirects' => [
            'max'             => 10,        // allow at most 10 redirects.
            'strict'          => true,      // use "strict" RFC compliant redirects.
            'referer'         => true,      // add a Referer header
            'protocols'       => ['https'], // only allow https URLs
            'on_redirect'     => $onRedirect,
            'track_redirects' => true
        ]
    ]);
    
    echo $res->getStatusCode();
    // 200
    
    echo $res->getHeaderLine('X-Guzzle-Redirect-History');
    // http://first-redirect, http://second-redirect, etc...
    

    auth

    • 摘要

      传入HTTP认证参数的数组来使用请求,该数组索引[0]为用户名、索引[1]为密码,索引[2]为可选的内置认证类型。传入 null 进入请求认证。

    • 类型

      arraystringnull

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::AUTH

    内置认证类型如下:

    • basic

      Authorization 头信息使用 HTTP基础认证 (如果没有指定的话为默认设置)。

    $client->request('GET', '/get', ['auth' => ['username', 'password']]);
    
    $client->request('GET', '/get', [
        'auth' => ['username', 'password', 'digest']
    ]);
    

    body

    • 摘要

      body 选项用来控制一个请求(比如:PUT, POST, PATCH)的主体部分。

    • 类型

      stringfopen() resourcePsrHttpMessageStreamInterface

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::BODY

    可以设置成下述类型:

    • string

      // You can send requests that use a string as the message body.
      $client->request('PUT', '/put', ['body' => 'foo']);
      
    • resource returned from fopen()

      // You can send requests that use a stream resource as the body.
      $resource = fopen('http://httpbin.org', 'r');
      $client->request('PUT', '/put', ['body' => $resource]);
      
    • PsrHttpMessageStreamInterface

      // You can send requests that use a Guzzle stream object as the body
      $stream = GuzzleHttpPsr7stream_for('contents...');
      $client->request('POST', '/post', ['body' => $stream]);
      

    cert

    • 摘要

      设置成指定PEM格式认证文件的路径的字符串,如果需要密码,需要设置成一个数组,其中PEM文件在第一个元素,密码在第二个元素。

    • 类型

      stringarray

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::CERT

    $client->request('GET', '/', ['cert' => ['/path/server.pem', 'password']]);
    

    cookies

    • 摘要

      声明是否在请求中使用cookie,或者要使用的cookie jar,或者要发送的cookie。

    • 类型

      GuzzleHttpCookieCookieJarInterface

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::COOKIES

    你必须声明cookie选项为 GuzzleHttpCookieCookieJarInterfacefalse

    $jar = new GuzzleHttpCookieCookieJar();
    $client->request('GET', '/get', ['cookies' => $jar]);
    

    connect_timeout

    • 摘要

      表示等待服务器响应超时的最大值,使用 0 将无限等待 (默认行为).

    • 类型

      float

    • 默认值

      0

    • 常量

      GuzzleHttpRequestOptions::CONNECT_TIMEOUT

    // Timeout if the client fails to connect to the server in 3.14 seconds.
    $client->request('GET', '/delay/5', ['connect_timeout' => 3.14]);
    

    debug

    • 摘要

      设置成 true 或设置成一个 fopen() 返回的流来启用调试输出发送请求的处理器, 比如,当使用cURL传输请求,cURL的 CURLOPT_VERBOSE 的冗长将会发出, 当使用PHP流,流处理的提示将会发生。 如果设置为true,输出到PHP标准输出文件,如果提供了PHP流,将会输出到流。

    • 类型

      boolfopen() resource

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::DEBUG

    $client->request('GET', '/get', ['debug' => true]);
    

    执行上面的例子将会输出类似下面的结果:

    * About to connect() to httpbin.org port 80 (#0)
    *   Trying 107.21.213.98... * Connected to httpbin.org (107.21.213.98) port 80 (#0)
    > GET /get HTTP/1.1
    Host: httpbin.org
    User-Agent: Guzzle/4.0 curl/7.21.4 PHP/5.5.7
    
    < HTTP/1.1 200 OK
    < Access-Control-Allow-Origin: *
    < Content-Type: application/json
    < Date: Sun, 16 Feb 2014 06:50:09 GMT
    < Server: gunicorn/0.17.4
    < Content-Length: 335
    < Connection: keep-alive
    <
    * Connection #0 to host httpbin.org left intact
    

    decode_content

    • 摘要

      声明是否自动解码 Content-Encoding 响应 (gzip, deflate等) 。

    • 类型

      stringbool

    • 默认值

      true

    • 常量

      GuzzleHttpRequestOptions::DECODE_CONTENT

    该选项可以用来控制Content-Encoding如何响应主体的,默认 decode_content 设置为 true,表示Guzzle将自动解码gzip,deflate等响应。

    当设置成 false ,响应的主体将不会被解码,意味着字节将毫无变化的通过处理器。

    // Request gzipped data, but do not decode it while downloading
    $client->request('GET', '/foo.js', [
        'headers'        => ['Accept-Encoding' => 'gzip'],
        'decode_content' => false
    ]);
    

    当设置成字符串,响应的字节将被解码,提供 decode_content 选项的字符串将作为请求的 Accept-Encoding 报文头。

    // Pass "gzip" as the Accept-Encoding header.
    $client->request('GET', '/foo.js', ['decode_content' => 'gzip']);
    

    delay

    • 摘要

      发送请求前延迟的毫秒数值

    • 类型

      integerfloat

    • 默认值

      null

    • 常量

      GuzzleHttpRequestOptions::DELAY

    expect

    • 摘要

      控制"Expect: 100-Continue"报文头的行为。

    • 类型

      boolinteger

    • 默认值

      1048576

    • 常量

      GuzzleHttpRequestOptions::EXPECT

    设置成 true 来为所有发送主体的请求启用 "Expect: 100-Continue" 报文头; 设置成 false 来为所有的请求禁用 "Expect: 100-Continue" 报文头; 设置成一个数值,有效载荷的大小必须大于预计发送的值,设置成数值将会为所有不确定有效载荷大小或主体不能确定指针位置的请求发送Expect报文头,

    默认情况下,当请求的主体大于1MB以及请求使用的HTTP/1.1,Guzzle将会添加 "Expect: 100-Continue" 报文头。

    form_params

    • 摘要

      用来发送一个 application/x-www-form-urlencoded POST请求.

    • 类型

      array

    • 常量

      GuzzleHttpRequestOptions::FORM_PARAMS

    关联数组由表单字段键值对构成,每个字段值可以是一个字符串或一个包含字符串元素的数组。 当没有准备 "Content-Type" 报文头的时候,将设置为 "application/x-www-form-urlencoded"。

    $client->request('POST', '/post', [
        'form_params' => [
            'foo' => 'bar',
            'baz' => ['hi', 'there!']
        ]
    ]);
    

    headers

    • 摘要

      要添加到请求的报文头的关联数组,每个键名是header的名称,每个键值是一个字符串或包含代表头字段字符串的数组。

    • 类型

      array

    • Defaults

      None

    • 常量

      GuzzleHttpRequestOptions::HEADERS

    // Set various headers on a request
    $client->request('GET', '/get', [
        'headers' => [
            'User-Agent' => 'testing/1.0',
            'Accept'     => 'application/json',
            'X-Foo'      => ['Bar', 'Baz']
        ]
    ]);
    

    创建Client的时候头信息可以作为默认选项添加,当头信息使用默认选项时,它们只能在请求没有包含特殊头信息的时候生效, 这包括了Client的 send()sendAsync() 方法,以及Client创建的请求(比如 request()requestAsync())。

    $client = new GuzzleHttpClient(['headers' => ['X-Foo' => 'Bar']]);
    
    // Will send a request with the X-Foo header.
    $client->request('GET', '/get');
    
    // Sets the X-Foo header to "test", which prevents the default header
    // from being applied.
    $client->request('GET', '/get', ['headers' => ['X-Foo' => 'test']);
    
    // Will disable adding in default headers.
    $client->request('GET', '/get', ['headers' => null]);
    
    // Will not overwrite the X-Foo header because it is in the message.
    use GuzzleHttpPsr7Request;
    $request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
    $client->send($request);
    
    // Will overwrite the X-Foo header with the request option provided in the
    // send method.
    use GuzzleHttpPsr7Request;
    $request = new Request('GET', 'http://foo.com', ['X-Foo' => 'test']);
    $client->send($request, ['headers' => ['X-Foo' => 'overwrite']]);
    

    http_errors

    • 摘要

      设置成 false 来禁用HTTP协议抛出的异常(如 4xx 和 5xx 响应),默认情况下HTPP协议出错时会抛出异常。

    • 类型

      bool

    • 默认值

      true

    • 常量

      GuzzleHttpRequestOptions::HTTP_ERRORS

    $client->request('GET', '/status/500');
    // Throws a GuzzleHttpExceptionServerException
    
    $res = $client->request('GET', '/status/500', ['http_errors' => false]);
    echo $res->getStatusCode();
    // 500
    

    json

    • 摘要

      json 选项用来轻松将JSON数据当成主体上传, 如果没有设置Content-Type头信息的时候会设置成 application/json

    • 类型

      能够 json_encode() 操作的PHP类型。

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::JSON

    $response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);
    

    这里的例子使用了 tap 中间件用来查看发送了什么请求。

    use GuzzleHttpMiddleware;
    
    // Grab the client's handler instance.
    $clientHandler = $client->getConfig('handler');
    // Create a middleware that echoes parts of the request.
    $tapMiddleware = Middleware::tap(function ($request) {
        echo $request->getHeader('Content-Type');
        // application/json
        echo $request->getBody();
        // {"foo":"bar"}
    });
    
    $response = $client->request('PUT', '/put', [
        'json'    => ['foo' => 'bar'],
        'handler' => $tapMiddleware($clientHandler)
    ]);
    

    multipart

    • 摘要

      设置请求的主体为 multipart/form-data 表单。

    • 类型

      array

    • 常量

      GuzzleHttpRequestOptions::MULTIPART

    multipart 的值是一个关联数组,每个元素包含以下键值对:

    • name: (string, required) 表单字段名称
    • contents: (StreamInterface/resource/string, required) 表单元素中要使用的数据
    • headers: (array) 可选的表单元素要使用的键值对数组
    • filename: (string) 可选的作为要发送的文件名称
    $client->request('POST', '/post', [
        'multipart' => [
            [
                'name'     => 'foo',
                'contents' => 'data',
                'headers'  => ['X-Baz' => 'bar']
            ],
            [
                'name'     => 'baz',
                'contents' => fopen('/path/to/file', 'r')
            ],
            [
                'name'     => 'qux',
                'contents' => fopen('/path/to/file', 'r'),
                'filename' => 'custom_filename.txt'
            ],
        ]
    ]);
    

    on_headers

    • 摘要

      回调函数,当响应的HTTP头信息被接收且主体部分还未开始下载的时候调用。

    • 类型

      callable

    • 常量

      GuzzleHttpRequestOptions::ON_HEADERS

    该回调接收 PsrHttpResponseInterface 对象。 如果该回调抛出异常,与响应相关的Promise将会接收到 GuzzleHttpExceptionRequestException 抛出的异常。

    在数据写入下游之前,你应该需要知道接收到的头信息与状态码。

    // Reject responses that are greater than 1024 bytes.
    $client->request('GET', 'http://httpbin.org/stream/1024', [
        'on_headers' => function (ResponseInterface $response) {
            if ($response->getHeaderLine('Content-Length') > 1024) {
                throw new Exception('The file is too big!');
            }
        }
    ]);
    

    on_stats

    • 摘要

      on_stats 允许你获取请求传输数据统计以及处理器在底层传输的详情. on_stats 是个回调,当处理器完成传输一个请求的时候被调用。 该回调被调用请求传输数据统计、接收到响应,或遇到错误,包含发送请求数据时间的总量。

    • 类型

      callable

    • 常量

      GuzzleHttpRequestOptions::ON_STATS

    该回调接收 GuzzleHttpTransferStats 对象。

    use GuzzleHttpTransferStats;
    
    $client = new GuzzleHttpClient();
    
    $client->request('GET', 'http://httpbin.org/stream/1024', [
        'on_stats' => function (TransferStats $stats) {
            echo $stats->getEffectiveUri() . "
    ";
            echo $stats->getTransferTime() . "
    ";
            var_dump($stats->getHandlerStats());
    
            // You must check if a response was received before using the
            // response object.
            if ($stats->hasResponse()) {
                echo $stats->getResponse()->getStatusCode();
            } else {
                // Error data is handler specific. You will need to know what
                // type of error data your handler uses before using this
                // value.
                var_dump($stats->getHandlerErrorData());
            }
        }
    ]);
    

    proxy

    • 摘要

      传入字符串来指定HTTP代理,或者为不同代理指定不同协议的数组。

    • 类型

      stringarray

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::PROXY

    传入字符串为所有协议指定一个代理:

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

    传入关联数组来为特殊的URI Scheme指定特色的HTTP代理(比如"http", "https") 提供一个 no 键值对来提供一组不需要使用代理的主机名。

    $client->request('GET', '/', [
        'proxy' => [
            'http'  => 'tcp://localhost:8125', // Use this proxy with "http"
            'https' => 'tcp://localhost:9124', // Use this proxy with "https",
            'no' => ['.mit.edu', 'foo.com']    // Don't use a proxy with these
        ]
    ]);
    

    query

    • 摘要

      要添加到请求的查询字符串的关联数组或查询字符串。

    • 类型

      arraystring

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::QUERY

    // Send a GET request to /get?foo=bar
    $client->request('GET', '/get', ['query' => ['foo' => 'bar']]);
    

    query 选项查询字符串指定,将会覆盖在请求时提供的查询字符串值。

    // Send a GET request to /get?foo=bar
    $client->request('GET', '/get?abc=123', ['query' => ['foo' => 'bar']]);
    

    sink

    • 摘要

      声明响应的主体部分将要保存的位置。

    • 类型

      string (path to file on disk)fopen() resourcePsrHttpMessageStreamInterface

    • 默认值

      PHP temp stream

    • 常量

      GuzzleHttpRequestOptions::SINK

    传入字符串来指定将要保存响应主体内容的文件的路径:

    $client->request('GET', '/stream/20', ['sink' => '/path/to/file']);
    

    传入 fopen() 返回的资源将响应写入PHP流:

    $resource = fopen('/path/to/file', 'w');
    $client->request('GET', '/stream/20', ['sink' => $resource]);
    

    传入 PsrHttpMessageStreamInterface 对象将响应写入打开的PSR-7流。

    $resource = fopen('/path/to/file', 'w');
    $stream = GuzzleHttpPsr7stream_for($resource);
    $client->request('GET', '/stream/20', ['save_to' => $stream]);
    

    ssl_key

    • 摘要

      指定一个链接到私有SSL密钥的PEM格式的文件的路径的字符串。 如果需要密码,设置成一个数组,数组第一个元素为链接到私有SSL密钥的PEM格式的文件的路径,第二个元素为认证密码。

    • 类型

      stringarray

    • 默认值

      None

    • 常量

      GuzzleHttpRequestOptions::SSL_KEY

    stream

    • 摘要

      设置成 true 流响应,而非下载响应。

    • 类型

      bool

    • 默认值

      false

    • 常量

      GuzzleHttpRequestOptions::STREAM

    $response = $client->request('GET', '/stream/20', ['stream' => true]);
    // Read bytes off of the stream until the end of the stream is reached
    $body = $response->getBody();
    while (!$body->eof()) {
        echo $body->read(1024);
    }
    

    synchronous

    • 摘要

      设置成 true 来通知HTTP处理器你要等待响应,这有利于优化。

    • 类型

      bool

    • 默认值

      none

    • 常量

      GuzzleHttpRequestOptions::SYNCHRONOUS

    verify

    • 摘要

      请求时验证SSL证书行为。设置成 true 启用SSL证书验证,默认使用操作系统提供的CA包。设置成 false 禁用证书验证(这是不安全的!)。设置成字符串启用验证,并使用该字符串作为自定义证书CA包的路径。

    • 类型

      boolstring

    • 默认值

      true

    • 常量

      GuzzleHttpRequestOptions::VERIFY

    // Use the system's CA bundle (this is 默认设置)
    $client->request('GET', '/', ['verify' => true]);
    
    // Use a custom SSL certificate on disk.
    $client->request('GET', '/', ['verify' => '/path/to/cert.pem']);
    
    // Disable validation entirely (don't do this!).
    $client->request('GET', '/', ['verify' => false]);
    

    并非所有的系统磁盘上都存在CA包,比如,Windows和OS X并没有通用的本地CA包。 当设置"verify" 为 true 时,Guzzle将尽力在你的操作系统中找到合适的CA包, 当使用cURL或PHP 5.6以上版本的流时,Guzzle将按以下顺序尝试查找CA包:

    1. 检查php.ini文件中是否设置了 openssl.cafile
    2. 检查php.ini文件中是否设置了 curl.cainfo
    3. 检查 /etc/pki/tls/certs/ca-bundle.crt 是否存在 (Red Hat, CentOS, Fedora; 由ca-certificates包提供)
    4. 检查 /etc/ssl/certs/ca-certificates.crt 是否存在 (Ubuntu, Debian; 由ca-certificates包提供)
    5. 检查 /usr/local/share/certs/ca-root-nss.crt 是否存在 (FreeBSD; 由ca_root_nss包提供)
    6. 检查 /usr/local/etc/openssl/cert.pem 是否存在 (OS X; 由homebrew提供)
    7. 检查 C:windowssystem32curl-ca-bundle.crt 是否存在 (Windows)
    8. 检查 C:windowscurl-ca-bundle.crt 是否存在 (Windows)

    查询的结果将缓存在内存中,以便同一进程后续快速调用。 然而在有些服务器如Apache中每个请求都在独立的进程中,你应该考虑设置 openssl.cafile 环境变量,指定到磁盘文件,以便整个过程都跳过。

    如果你不需要特殊的证书包,可以使用Mozilla提供的通用CA包,你可以在 这里 下载(由cURL的维护者提供)。 一旦磁盘有了CA包,你可以设置PHP ini配置文件,指定该文件的路径到变量 openssl.cafile 中,这样就可以在请求中省略 "verify" 参数。 你可以在 cURL 网站 发现更多关于SSL证书的细节。

    timeout

    • 摘要

      请求超时的秒数。使用 0 无限期的等待(默认行为)。

    • 类型

      float

    • 默认值

      0

    • 常量

      GuzzleHttpRequestOptions::TIMEOUT

    // Timeout if a server does not return a response in 3.14 seconds.
    $client->request('GET', '/delay/5', ['timeout' => 3.14]);
    // PHP Fatal error:  Uncaught exception 'GuzzleHttpExceptionRequestException'
    

    version

    • 摘要

      请求要使用到的协议版本。

    • 类型

      string, float

    • 默认值

      1.1

    • 常量

      GuzzleHttpRequestOptions::VERSION

    // Force HTTP/1.0
    $request = $client->request('GET', '/get', ['version' => 1.0]);
    
  • 相关阅读:
    简易发号SQL,可用于生成指定前缀自增序列--改进版
    关于【【故障公告】数据库服务器 CPU 近 100% 引发的故障(源于 .NET Core 3.0 的一个 bug)】IS NOT NULL测试
    简易发号SQL,可用于生成指定前缀自增序列,如订单号,生成优惠券码等
    [EntityFramework]记录Linq中如何比较数据库中Timestamp列的方法(如大于0x00000000000007D1的记录)
    [高并发]抢红包设计(使用redis)
    [.Net跨平台]部署DTCMS到Jexus遇到的问题及解决思路--验证码
    [.Net跨平台]部署DTCMS到Jexus遇到的问题及解决思路---部署
    【迷你微信】基于MINA、Hibernate、Spring、Protobuf的即时聊天系统 :1.技术简介之Mina连接
    Unity光晕剑效果的Shader简单实现
    Unity3D 调用Android与IOS的剪贴板
  • 原文地址:https://www.cnblogs.com/makalochen/p/13558570.html
Copyright © 2011-2022 走看看