【问题标题】:Can't set Guzzle Content Type无法设置 Guzzle 内容类型
【发布时间】:2015-03-29 01:51:04
【问题描述】:

我正在尝试这样请求:

$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 的情况下设置的。 我做错了什么?

【问题讨论】:

    标签: php laravel curl guzzle


    【解决方案1】:

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

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

    【讨论】:

    • 显然 GuzzleHTTP 6.2 中不再有“默认”设置,创建客户端时传递的每个设置都成为此客户端实例的默认设置。
    【解决方案2】:

    狂饮 6

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

    你有两个选择。

    选项 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

    【讨论】:

      【解决方案3】:

      我在使用 Hubspot API 时遇到了同样的问题,需要将 application/json 设置为 POST 请求的 Content-Type。

      我是这样解决的

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

      我希望这会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-28
        • 1970-01-01
        • 2014-03-15
        • 1970-01-01
        • 1970-01-01
        • 2012-12-30
        • 2014-11-05
        相关资源
        最近更新 更多