JSON에서 Guzle을 사용하여 POST 요청을 보내려면 어떻게 해야 하나요?

할 수 있는 올바른 방법 아는 사람?postJSON 사용Guzzle?

$request = $this->client->post(self::URL_REGISTER,array(

'content-type' => 'application/json'
),array(json_encode($_POST))); 

나는 그것을 받았다.internal server error서버로부터의 응답.Chrome을 사용하여 동작합니다.Postman.



질문에 대한 답변



Guzzle 5, 6, 7의 경우 다음과 같이 수행합니다.

use GuzzleHttpClient;
$client = new Client();
$response = $client->post('url', [
GuzzleHttpRequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...] ]); 

문서




단순하고 기본적인 방법(guzle6):

$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>'; 



거즐 <= 4:

미가공 포스트 요구이므로 본문에 JSON을 삽입하면 문제가 해결됩니다.

$request = $this->client->post(
$url,
[
'content-type' => 'application/json'
], ); $request->setBody($data); #set body! $response = $request->send(); 



이것은 나에게 효과가 있었다(Guzle 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()); 



$client = new GuzzleHttpClient();
$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();