2

I need to send this body as JSON, using that header to authenticate.

$headers = array( 
    'Authorization' => "Bearer ".$token->access_token,
    'Content-Type' => 'application/json',
);

$body = [ 
    'code1' => '444444',
    'code2' => 'zzzzz'
];

Firts approach, this code does not work:

 $myhttp = new Client();

 $res = $myhttp->request('POST', 'https://www.xxxxxxxxxxxx',
     [
         'headers' => ['Content-Type' => 'application/json',"Authorization" => "Bearer ".$token->access_token],
         'json' => ['code1' => '444444','code2' => 'zzzz']
     ]
 );

Second approach neither:

$body= json_encode($body);

$res = $myhttp->request('POST', 'https://www.xxxxxxxxxxxx',
    [
        'headers' => ['Content-Type' => 'application/json',"Authorization" => "Bearer ".$token->access_token],
        'body' => $body]
    ]
);   

Third approach neither: When trying to use body, Guzzle tells me that this is deprecated and now "form_params" is used, but form_params accepts only arrays, not json.

$body= json_encode($body); // encode to json!

$res = $myhttp->request('POST', 'https://www.xxxxxxxxxxxx',
    [
        'headers' => ['Content-Type' => 'application/json',"Authorization" => "Bearer ".$token->access_token],
        'form_params' => $body]
    ]
);  
Jakub Muda
  • 6,008
  • 10
  • 37
  • 56
rendor9
  • 172
  • 2
  • 10

1 Answers1

0

The best way is to use GuzzleHttp\RequestOptions::JSON from Guzzle :

$client = new Client();

$response = $client->post('https://www.xxxxxxxxxxxx', [
    GuzzleHttp\RequestOptions::JSON => ['code1' => '444444','code2' => 'zzzz']
]);
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84