I would like to attach authentication information in the header of an HTTP request using HttpClientInterface.
(I already have 45 other methods that work very well) but my problem occurs when I try to send a file with the multipart/form-data content-type.
I take the code from the original documentation below to stay on a very simple case but I can't join my data in the generated ones.
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\Multipart\FormDataPart;
$formFields = [
'regular_field' => 'some value',
'file_field' => DataPart::fromPath('/path/to/uploaded/file')
];
$formData = new FormDataPart($formFields);
$client->request('POST', 'https://...', [
'headers' => $formData->getPreparedHeaders()->toArray(),
'body' => $formData->bodyToIterable(),
]);
Here's what I'm trying to do
$myHeader = [
'Authorization' => 'Bearer ' . $this->getUser()->getToken()
];
$params = [
'headers' => array_merge($myHeader, $formData->getPreparedHeaders()->toArray()),
'body' => $formData->bodyToIterable(),
];
And here's how it's translated so the API doesn't understand what I send it and return me back a 400 bad request
"headers" => [
"Authorization" => "Bearer eecd39xxxxxxxxede8e66433d3aea693"
0 => "Content-Type: multipart/form-data; boundary=ujDYAsPF"
]
It's a relatively common case in principle so I guess there is a solution? thank you.
When you use
getPreparedHeaders
you have to add your own headers to theHeader
object it returns and then usetoArray()
to pass it to your request.It will give you the proper key/value header