2

How can I pass parameters to the http client get request in json format:

$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);

$params = '{"data1":"",
"data2":"mydata"
"data3":"mydata",
"data3":"mydata",
"data5":"mydata"}';

$url = 'https://myendpointurl';
try {
  $response = $client->get($url, array(
      'headers' => array('Accept' => 'text/plain'),
    )
  );
  $data = json_decode($response->getBody());
}
catch (RequestException $e) {
  watchdog_exception('my_module', $e->getMessage());
}

Where I need to put $params variable in my code?

1 Answer 1

2

You can add it to the request like so:

use Drupal\Component\Serialization\Json;
...
$response = $client->get($url, [
    'headers' => ['Accept' => 'text/plain'],
    'json' => Json::decode($params),
]);
1
  • what's the advantage of using Json::decode($params), over json_decode?
    – awm
    Sep 26, 2017 at 19:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.