Skip to content

Commit ad21dbe

Browse files
[HttpClient] Fix Content-Length header when possible
1 parent 5c67f40 commit ad21dbe

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/Symfony/Component/HttpClient/HttpClientTrait.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,11 @@ private static function prepareRequest(?string $method, ?string $url, array $opt
8686

8787
if (isset($options['body'])) {
8888
$options['body'] = self::normalizeBody($options['body']);
89+
90+
if (\is_string($options['body']) && (string) \strlen($options['body']) !== substr($h = $options['normalized_headers']['content-length'][0] ?? '', 16)) {
91+
$options['normalized_headers']['content-length'][0] = substr_replace($h, \strlen($options['body']), 16);
92+
$options['headers'] = array_merge(...array_values($options['normalized_headers']) ?: [[]]);
93+
}
8994
}
9095

9196
if (isset($options['peer_fingerprint'])) {

src/Symfony/Component/HttpClient/Tests/HttpClientTestCase.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,21 @@ public function testDebugInfoOnDestruct()
180180
$this->assertNotEmpty($traceInfo['debug']);
181181
}
182182

183+
public function testFixContentLength()
184+
{
185+
$client = $this->getHttpClient(__FUNCTION__);
186+
187+
$response = $client->request('POST', 'http://localhost:8057/post', [
188+
'body' => 'abc=def',
189+
'headers' => ['Content-Length: 4'],
190+
191+
]);
192+
193+
$body = $response->toArray();
194+
195+
$this->assertSame(['abc' => 'def', 'REQUEST_METHOD' => 'POST'], $body);
196+
}
197+
183198
public function testNegativeTimeout()
184199
{
185200
$client = $this->getHttpClient(__FUNCTION__);

0 commit comments

Comments
 (0)