簡體   English   中英

如何使用Guzzle6發出此POST請求

[英]How do I make this POST request with Guzzle6

我工作的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做到這一點。

以下是官方文檔中的示例,您如何使用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選項。

您可以使用幫助標題選項輕松設置任何標題。

您可以在此處找到更多信息Guzzle升級指南(5.0到6.0)

這是從我的一個項目中復制的一些代碼:

$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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM