无法设置Guzzle内容类型

时间:2015-01-29 18:00:07

标签: php laravel curl 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),
]);

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

3 个答案:

答案 0 :(得分:12)

好的..问题是我在默认设置之外设置了正文和标题。解决方案是:

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

答案 1 :(得分:6)

Guzzle 6

  

Guzzle会将Content-Type标头设置为   没有Content-Type标头时application/x-www-form-urlencoded   已经在场了。

您有2个选项。

选项1:直接在客户端上

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

选项2:基于每个请求

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

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

您可以参考Guzzle 6: Request Options

答案 2 :(得分:0)

我在Hubspot API上遇到了同样的问题,该问题要求将application/json设置为POST请求的内容类型。

我是通过这种方式解决的

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

然后按常规方式执行我的请求

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); }

我希望这会有所帮助。