php 无法设置 Guzzle 内容类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28221462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:45:22  来源:igfitidea点击:

Can't set Guzzle Content Type

phplaravelcurlguzzle

提问by Bug

I'm trying to request this way:

我正在尝试以这种方式请求:

$body = [];
$body['holder_name'] = $full_name;
$body['bank_code'] = $bank_number;
$body['routing_number'] = $branch_number;
$body['account_number'] = $account_number;
$body['type'] = 'checking';

$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'headers'  => ['content-type' => 'application/json', 'Accept' => 'application/json'],
    'defaults' => [
         'auth' => [$publishable_key, ''],
],
    'body' => json_encode($body),
]);

The problem is that this request is being set without Content-Type. What am I doing wrong?

问题是此请求是在没有 Content-Type 的情况下设置的。我究竟做错了什么?

回答by Bug

Ok .. the problem was that I was setting body and headers outside of defautls. the solution is:

好的.. 问题是我在 defautls 之外设置了正文和标题。解决办法是:

$client = new GuzzleHttp\Client([
'base_url' => [$url, []],
'defaults' => [
     'auth' => [$publishable_key, ''],
     'headers'  => ['content-type' => 'application/json', 'Accept' => 'application/json'],
     'body' => json_encode($body),
],
]);

回答by Mick

Guzzle 6

狂饮6

Guzzle will set the Content-Type header to application/x-www-form-urlencodedwhen no Content-Type header is already present.

Guzzle 会将 Content-Type 标头设置为 application/x-www-form-urlencoded不存在 Content-Type 标头时。

You have 2 options.

您有 2 个选择。

Option 1: On the Client directly

Option 1: On the Client directly

$client = new GuzzleHttp\Client(
    ['headers' => [
        'Content-Type' => 'application/json'
        ]
    ]
);

Option 2: On a Per Request basis

Option 2: On a Per Request basis

// Set various headers on a request
$client = new GuzzleHttp\Client();

$client->request('GET', '/whatever', [
    'headers' => [
        'Content-Type' => 'application/json'
    ]
]);


You can refer to Guzzle 6: Request Options

可以参考Guzzle 6:请求选项