Skip to content

Commit

Permalink
JdkClientHttpRequest does not support Content-Length 0
Browse files Browse the repository at this point in the history
This commit ensures the correct HttpRequest.BodyPublisher is used with
Content-Length 0.

Closes gh-31451
  • Loading branch information
poutsma committed Oct 23, 2023
1 parent 3cb700c commit cb4d44b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023-2023 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -129,9 +129,12 @@ private HttpRequest.BodyPublisher bodyPublisher(HttpHeaders headers, @Nullable B
BYTE_MAPPER, this.executor);

long contentLength = headers.getContentLength();
if (contentLength != -1) {
if (contentLength > 0) {
return HttpRequest.BodyPublishers.fromPublisher(outputStreamPublisher, contentLength);
}
else if (contentLength == 0) {
return HttpRequest.BodyPublishers.noBody();
}
else {
return HttpRequest.BodyPublishers.fromPublisher(outputStreamPublisher);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* Copyright 2023-2023 the original author or authors.
* Copyright 2002-2023 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Expand All @@ -24,6 +24,7 @@
import org.junit.jupiter.api.Test;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.lang.Nullable;

Expand Down Expand Up @@ -67,12 +68,22 @@ public void httpMethods() throws Exception {

@Test
public void customizeDisallowedHeaders() throws IOException {
ClientHttpRequest request = factory.createRequest(URI.create(this.baseUrl + "/status/299"), HttpMethod.PUT);
ClientHttpRequest request = this.factory.createRequest(URI.create(this.baseUrl + "/status/299"), HttpMethod.PUT);
request.getHeaders().set("Expect", "299");

try (ClientHttpResponse response = request.execute()) {
assertThat(response.getStatusCode()).as("Invalid status code").isEqualTo(HttpStatusCode.valueOf(299));
}
}

@Test // gh-31451
public void contentLength0() throws IOException {
BufferingClientHttpRequestFactory bufferingFactory = new BufferingClientHttpRequestFactory(this.factory);
ClientHttpRequest request = bufferingFactory.createRequest(URI.create(this.baseUrl + "/methods/get"), HttpMethod.GET);

try (ClientHttpResponse response = request.execute()) {
assertThat(response.getStatusCode()).as("Invalid response status").isEqualTo(HttpStatus.OK);
}
}

}

0 comments on commit cb4d44b

Please sign in to comment.