Home > Back-end >  Laravel CURL - Passing a string to HTTP URL (Postfields)
Laravel CURL - Passing a string to HTTP URL (Postfields)

Time:06-11

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()));

CodePudding user response:

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.

CodePudding user response:

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

  • Related