简体   繁体   English

无法设置 Guzzle 内容类型

[英]Can't set Guzzle Content Type

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.问题是此请求是在没有 Content-Type 的情况下设置的。 What am I doing wrong?我究竟做错了什么?

Ok .. the problem was that I was setting body and headers outside of defautls.好的.. 问题是我在 defautls 之外设置了正文和标题。 the solution is:解决办法是:

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

Guzzle 6狂饮6

Guzzle will set the Content-Type header to application/x-www-form-urlencoded when no Content-Type header is already present.当没有 Content-Type 标头存在时,Guzzle 会将 Content-Type 标头设置为application/x-www-form-urlencoded

You have 2 options.您有 2 个选择。

Option 1: On the Client directly选项 1:直接在客户端上

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

Option 2: On a Per Request basis选项 2:基于每个请求

// 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:请求选项

I was encountering the same issue with the Hubspot API that requires to set application/json as Content-Type for POST requests.我在 Hubspot API 中遇到了同样的问题,需要将application/json设置为 POST 请求的 Content-Type。

I fixed it this way我是这样修的

$client = new Client([
    'base_uri' => 'https://api.hubapi.com/',
    'timeout'  => 5,
    'headers' => ['Content-Type' => 'application/json']
]);

And then performing my requests the regular way然后以常规方式执行我的请求

try
{
    $response = $client->request('POST', '/contacts/v1/contact/email/test@test.com/profile',
    ['query' => MY_HUBSPOT_API_KEY, 'body' => $body]);
}
catch (RequestException $e) { print_r($e); }

I hope this helps.我希望这有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM