ForceMan
ForceMan

Reputation: 25

Laravel CURL - Passing a string to HTTP URL (Postfields)

I use Laravel 9 and the built-in method Http::withHeaders ($headers)->post($url, $data).

In the $data variable, I pass the string that resulted from http_build_request with the "&" separator. But Laravel tries to make an array out of it and send data.

The API service returns me an error. Please tell me how you can force Laravel to pass exactly a STRING(!), and not an array?

My code:

$array = [
            'key1' => 'value1',
            'key2' => 'value2',
            // etc...
];
$headers = [
            'Content-Type' => 'application/x-www-form-urlencoded',
            'HMAC' => $hmac
];

$data = http_build_query($array, '', '&');
$response = Http::withHeaders($headers)->post($api_url, $data);
return json_decode($response->getBody()));

Upvotes: 0

Views: 1918

Answers (2)

Jelinskyy
Jelinskyy

Reputation: 21

If you sending it as x-www-form-urlencoded i gues u should be able to pass the data inside request body.

 $response = Http::withHeaders($headers)
      ->withBody($data)
      ->asForm()
      ->post($api_url);

however, i am not sure if this will work

Upvotes: 2

Atlas-Pio
Atlas-Pio

Reputation: 1153

Have you tried, asForm?

$response = Http::withHeaders($headers)->asForm()->post($api_url, $data);

If you would like to send data using the application/x-www-form-urlencoded content type, you should call the asForm method before making your request.

Upvotes: 2

Related Questions