使用PHP Guzzle HTTP 6发送带有已编码数据的JSON [英] Using PHP Guzzle HTTP 6 to send JSON with data that is already encoded

查看:1038
本文介绍了使用PHP Guzzle HTTP 6发送带有已编码数据的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发送POST请求,该请求包含带有以下标头的原始JSON字符串:Content-Type: application/json.

I am trying to send a POST request which contains a raw JSON string with the following header: Content-Type: application/json.

通过查看文档,我可以看到我可以做类似的事情...

From looking at the docs, I can see that I can do something like this...

$data = ['x' => 1, 'y' => 2, 'z' => 3];
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
    'json' => $data,
];
$client->post('http://example.com', $options);

我的问题是,到现在为止,$data已经被json_encode了.

My problem is that when I get to this point, $data has already been json_encode'd.

我尝试了以下方法,但是它不起作用.

I have tried the following but it does not work.

$data = json_encode(['x' => 1, 'y' => 2, 'z' => 3]);
$client = new \GuzzleHttp\Client($guzzleConfig);
$options = [
    'body' => $data,
    'headers' => ['Content-Type' => 'application/json'],
];
$client->post('http://example.com', $options);

我的问题是:我可以对已编码的数组使用json选项吗?还是我可以简单地设置Content-Type标头?

My question is: can I use the json option with an already-encoded array? Or is there a way for me to simply set the Content-Type header?

推荐答案

根据guzzle的文档 http://docs.guzzlephp.org/en/latest/request-options.html#json

According to guzzle's docs http://docs.guzzlephp.org/en/latest/request-options.html#json

您可以将已经编码的json直接传递到body参数中

You can pass the already encoded json directly into the body parameter

注意:此请求选项不支持自定义内容类型 标头或PHP的json_encode()函数中的任何选项.如果你 需要自定义这些设置,那么您必须传递JSON编码 您可以使用body request选项将数据输入到请求中,然后 必须使用标头请求指定正确的Content-Type标头 选项.

Note This request option does not support customizing the Content-Type header or any of the options from PHP's json_encode() function. If you need to customize these settings, then you must pass the JSON encoded data into the request yourself using the body request option and you must specify the correct Content-Type header using the headers request option.

此选项不能与body,form_params或multipart一起使用

This option cannot be used with body, form_params, or multipart

这篇关于使用PHP Guzzle HTTP 6发送带有已编码数据的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆