【问题标题】:What is the correct way to send a JSON POST and header with Guzzle 7?使用 Guzzle 7 发送 JSON POST 和标头的正确方法是什么?
【发布时间】:2020-11-08 23:13:28
【问题描述】:

我需要将此正文作为 JSON 发送,并使用该标头进行身份验证。

$headers = array( 
    'Authorization' => "Bearer ".$token->access_token,
    'Content-Type' => 'application/json',
);

$body = [ 
    'code1' => '444444',
    'code2' => 'zzzzz'
];

第一种方法,此代码不起作用:

 $myhttp = new Client();

 $res = $myhttp->request('POST', 'https://www.xxxxxxxxxxxx',
     [
         'headers' => ['Content-Type' => 'application/json',"Authorization" => "Bearer ".$token->access_token],
         'json' => ['code1' => '444444','code2' => 'zzzz']
     ]
 );

第二种方法都没有:

$body= json_encode($body);

$res = $myhttp->request('POST', 'https://www.xxxxxxxxxxxx',
    [
        'headers' => ['Content-Type' => 'application/json',"Authorization" => "Bearer ".$token->access_token],
        'body' => $body]
    ]
);   

第三种方法都没有: 当尝试使用 body 时,Guzzle 告诉我这已被弃用,现在使用 "form_params",但 form_params 只接受数组,而不接受 json。

$body= json_encode($body); // encode to json!

$res = $myhttp->request('POST', 'https://www.xxxxxxxxxxxx',
    [
        'headers' => ['Content-Type' => 'application/json',"Authorization" => "Bearer ".$token->access_token],
        'form_params' => $body]
    ]
);  

【问题讨论】:

    标签: laravel guzzle6 guzzle


    【解决方案1】:

    最好的方法是使用来自 Guzzle 的GuzzleHttp\RequestOptions::JSON:

    $client = new Client();
    
    $response = $client->post('https://www.xxxxxxxxxxxx', [
        GuzzleHttp\RequestOptions::JSON => ['code1' => '444444','code2' => 'zzzz']
    ]);
    

    【讨论】:

    • GuzzleHttp\RequestOptions' not found ...正在尝试解决。
    • 我重新安装了 laravel 和 guzzle 7,同样,GuzzleHttp \ RequestOptions' not found...ufff
    • @rendor9 重新加载所有类composer dump-autoload
    • 我做composer dump-autoload,答案是GuzzleHttp\RequestOptions' not found
    猜你喜欢
    • 2016-04-16
    • 1970-01-01
    • 1970-01-01
    • 2018-01-12
    • 2014-07-17
    • 2018-07-18
    • 1970-01-01
    • 2018-09-22
    • 2021-05-09
    相关资源
    最近更新 更多