有人知道用Guzzle发布JSON的正确方法吗?
$request = $this->client->post(self::URL_REGISTER,array(
'content-type' => 'application/json'
),array(json_encode($_POST)));
我从服务器得到一个内部服务器错误响应。它使用Chrome邮差工作。
有人知道用Guzzle发布JSON的正确方法吗?
$request = $this->client->post(self::URL_REGISTER,array(
'content-type' => 'application/json'
),array(json_encode($_POST)));
我从服务器得到一个内部服务器错误响应。它使用Chrome邮差工作。
当前回答
这适用于我的Guzzle 6.2:
$gClient = new \GuzzleHttp\Client(['base_uri' => 'www.foo.bar']);
$res = $gClient->post('ws/endpoint',
array(
'headers'=>array('Content-Type'=>'application/json'),
'json'=>array('someData'=>'xxxxx','moreData'=>'zzzzzzz')
)
);
根据文档guzzle做json_encode
其他回答
上述答案对我来说并不管用。但这对我来说很好。
$client = new Client('' . $appUrl['scheme'] . '://' . $appUrl['host'] . '' . $appUrl['path']);
$request = $client->post($base_url, array('content-type' => 'application/json'), json_encode($appUrl['query']));
你可以使用硬编码的json属性作为键,或者你可以方便地使用GuzzleHttp\RequestOptions:: json常量。
下面是使用硬编码的json字符串的例子。
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
'json' => ['foo' => 'bar']
]);
见文档。
对于Guzzle <= 4:
这是一个原始的post请求,所以把JSON放在body中解决了这个问题
$request = $this->client->post(
$url,
[
'content-type' => 'application/json'
],
);
$request->setBody($data); #set body!
$response = $request->send();
解决方案$客户端->请求('POST',…
对于那些使用$client->请求的人,这是如何创建JSON请求的:
$client = new Client();
$res = $client->request('POST', "https://some-url.com/api", [
'json' => [
'paramaterName' => "parameterValue",
'paramaterName2' => "parameterValue2",
]
'headers' => [
'Content-Type' => 'application/json',
]
]);
Guzzle JSON请求参考
来自@user3379466的答案可以通过设置$data来工作,如下所示:
$data = "{'some_key' : 'some_value'}";
我们的项目需要的是将一个变量插入到json字符串中的数组中,我这样做如下(如果这有助于任何人):
$data = "{\"collection\" : [$existing_variable]}";
因此,与$existing_variable是,说,90210,你得到:
echo $data;
//{"collection" : [90210]}
另外值得注意的是,你可能还想设置'Accept' => 'application/json'以防你碰到的端点关心这类事情。