Drupal - How to send POST request to https using \Drupal::httpClient()?
The error message should inform you what is going on. You are using a self-signed certificate locally. This probably won't be an issue on your production sites, but this is not really useful for local development.
Inspect the \Drupal::httpClient()
static method you may discover that it uses the http_client_factory:fromOptions
service. Use this directly allows you to pass options into Guzzle to allow requests to sites using self-signed certificates.
$clientFactory = \Drupal::service('http_client_factory');
$client = $clientFactory->fromOptions(['verify' => FALSE]);
Obviously this is not ideal. You should probably parameterize the URL that you are using instead of hard coding the URL. Then locally you can test without a self-signed cert or HTTPS. Or parameterize the options you pass into Guzzle so that verify => TRUE
when you're on production. It is not recommended to set it to FALSE and this is a security risk.
We must pass the post values in http_client via form_params . Here down is one of my code to make OAuth2 authentication to another drupal 8 REST api being used simple_oauth module.
$response = \Drupal::httpClient()->post($base_url . '/oauth/token', [
'verify' => true,
'form_params' => ['grant_type'=> 'password',
'client_id' => 'CLIENT-ID',
'client_secret'=> 'CLIENT-SECRET',
'scope'=>'',
'username'=>'admin',
'password'=>'admin',],
'headers' => [
'Content-type' => 'application/x-www-form-urlencoded',
],
])->getBody()->getContents();