October 21, 2024
Chicago 12, Melborne City, USA
PHP

API POST Request using HttpClientInterface


I am trying to do a POST request to an API using Symfony HttpClientInterface. But I am struggling as it always throwing 400 error. But when using cUrl it is working fine.

$data = [
        'parameter1' => 'xxxxx',
        'parameter2' => 'xxxxx',
        'parameter3' => 'xxxxx',
        'parameter4' => 'xxxxx',
        'parameter5' => 'xxxxx',
        'parameter6' => 'xxxxx',
        'parameter7' => 'xxxxx',
        'parameter8' => 'xxxxx'
    ];

$postData = http_build_query($data);
            $ch = curl_init($URL);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_HTTPHEADER, [
                'Content-Type: application/x-www-form-urlencoded'
            ]);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            $response = curl_exec($ch);

Symfony by usnig HttpClientInterface (not working)

$response = $this->tokenClient->request('POST', $url, [
    'headers' => [
        'Content-Type' => 'application/x-www-form-urlencoded',
    ],
    'body' => [
        'parameter1' => 'xxxxx',
        'parameter2' => 'xxxxx',
        'parameter3' => 'xxxxx',
        'parameter4' => 'xxxxx',
        'parameter5' => 'xxxxx',
        'parameter6' => 'xxxxx',
        'parameter7' => 'xxxxx',
        'parameter8' => 'xxxxx'
    ]
]);

Anyone has an idea why it’s not working with HttpClientInterface and how can I make it work?



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video