【问题标题】:How do I make this POST request with Guzzle6如何使用 Guzzle6 发出此 POST 请求
【发布时间】:2015-09-11 08:34:32
【问题描述】:

我的 Guzzle5 代码大致如下:

$guzzle = new \GuzzleHttp\Client();
$request = $guzzle->createRequest('POST', $url);
$request->setHeader('Authorization', 'Bearer ' . $token);
$postBody = $request->getBody();
$postBody->setField('name', 'content');//several times
if (check for file) {
    $postBody->addFile(new \GuzzleHttp\Post\PostFile('name', fopen(...));
}
$response = $guzzle->send($request);

设置标题并添加文件是什么,我不知道如何使用 Guzzle6 执行此操作。

【问题讨论】:

    标签: php post guzzle


    【解决方案1】:

    这是官方文档中的一个示例,您如何使用 Guzzle 6 设置标头并将文件添加到您的 POST 请求中:

    $client = new \GuzzleHttp\Client();
    $client->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'
            ],
        ]
    ]);
    

    multipart 选项将请求正文设置为 multipart/form-data 表单,如果您不需要处理文件,则可以使用 form_params 而不是 multipart 选项。

    您可以使用headers 选项轻松设置任何标题。

    您可以在这里找到更多信息Guzzle Upgrade Guide (5.0 to 6.0)

    【讨论】:

      【解决方案2】:

      这是从我的一个项目中复制的一些代码:

      $client = new GuzzleHttp\Client();
      $url = 'someurl.com/api';
      $body = json_encode([
          'variable1' => 'this',
          'variable2' => 'that'
      ]);
      
      
      $response = $client->post($url, [
          'headers' => [
              'header_variable1' => 'foo',
              'header_variable2' => 'bar'
          ],
          'json' => true,
          'timeout' => 3,
          'body' => $body
      ]);
      
      $data = $response->json();
      

      【讨论】:

        猜你喜欢
        • 2018-05-17
        • 2014-06-20
        • 2019-09-28
        • 2016-08-25
        • 2022-11-02
        • 2011-05-11
        • 2019-04-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多