有人知道用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邮差工作。
当前回答
我使用下面的代码,工作非常可靠。
JSON数据在参数$request中传递,特定的请求类型在变量$searchType中传递。
该代码包含一个陷阱,用于检测和报告不成功或无效的调用,然后返回false。
如果调用成功,json_decode ($result->getBody(), $return=true)返回一个结果数组。
public function callAPI($request, $searchType) {
$guzzleClient = new GuzzleHttp\Client(["base_uri" => "https://example.com"]);
try {
$result = $guzzleClient->post( $searchType, ["json" => $request]);
} catch (Exception $e) {
$error = $e->getMessage();
$error .= '<pre>'.print_r($request, $return=true).'</pre>';
$error .= 'No returnable data';
Event::logError(__LINE__, __FILE__, $error);
return false;
}
return json_decode($result->getBody(), $return=true);
}
其他回答
$client = new \GuzzleHttp\Client();
$body['grant_type'] = "client_credentials";
$body['client_id'] = $this->client_id;
$body['client_secret'] = $this->client_secret;
$res = $client->post($url, [ 'body' => json_encode($body) ]);
$code = $res->getStatusCode();
$result = $res->json();
对于《Guzzle 5》,《Guzzle 6》和《Guzzle 7》,你是这样做的:
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);
Docs
来自@user3379466的答案可以通过设置$data来工作,如下所示:
$data = "{'some_key' : 'some_value'}";
我们的项目需要的是将一个变量插入到json字符串中的数组中,我这样做如下(如果这有助于任何人):
$data = "{\"collection\" : [$existing_variable]}";
因此,与$existing_variable是,说,90210,你得到:
echo $data;
//{"collection" : [90210]}
另外值得注意的是,你可能还想设置'Accept' => 'application/json'以防你碰到的端点关心这类事情。
简单而基本的方法(guzzle6):
$client = new Client([
'headers' => [ 'Content-Type' => 'application/json' ]
]);
$response = $client->post('http://api.com/CheckItOutNow',
['body' => json_encode(
[
'hello' => 'World'
]
)]
);
为了获得响应状态代码和主体的内容,我这样做:
echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';
你可以使用硬编码的json属性作为键,或者你可以方便地使用GuzzleHttp\RequestOptions:: json常量。
下面是使用硬编码的json字符串的例子。
use GuzzleHttp\Client;
$client = new Client();
$response = $client->post('url', [
'json' => ['foo' => 'bar']
]);
见文档。