有没有人知道post
使用JSON 的正确方法Guzzle
?
$request = $this->client->post(self::URL_REGISTER,array( 'content-type' => 'application/json' ),array(json_encode($_POST)));
我收到internal server error
服务器的回复.它适用于Chrome Postman
.
简单而基本的方式(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>';
对于Guzzle <= 4:
这是一个原始的帖子请求,因此将JSON放入正文解决了问题
$request = $this->client->post($url,array( 'content-type' => 'application/json' ),array()); $request->setBody($data); #set body! $response = $request->send(); return $response;
这对我有用(使用Guzzle 6)
$client = new Client(); $result = $client->post('http://api.example.com', [ 'json' => [ 'value_1' => 'number1', 'Value_group' => array("value_2" => "number2", "value_3" => "number3") ] ]); echo($result->getBody()->getContents());
对于Guzzle 5和6,您可以这样做:
use GuzzleHttp\Client; $client = new Client(); $response = $client->post('url', [ GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] ]);
文件
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 \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();
$client = new \GuzzleHttp\Client(['base_uri' => 'http://example.com/api']); $response = $client->post('/save', [ 'json' => [ 'name' => 'John Doe' ] ]); return $response->getBody();