无法设置Guzzle内容类型

Bug*_*Bug 7 php curl laravel guzzle

我试图这样请求:

$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),
]);
Run Code Online (Sandbox Code Playgroud)

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

Bug*_*Bug 13

好吧..问题是我在defautls之外设置了body和header.解决方案是:

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


Mic*_*ick 7

Guzzle 6

application/x-www-form-urlencoded当没有Content-Type标头已存在时,Guzzle会将Content-Type标头设置为 .

你有2个选择.

Option 1: On the Client directly

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

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'
    ]
]);
Run Code Online (Sandbox Code Playgroud)

您可以参考Guzzle 6:请求选项