Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8358942

HttpClient adds Content-Length: 0 for a GET request with a BodyPublishers.noBody()

XMLWordPrintable

    • b21

      JDK-8283544 addressed the issue where HttpClient was adding a Content-Length: 0 request header for a GET request. The test/jdk/java/net/httpclient/ContentLengthHeaderTest.java, which was added as part of that fix, continues to reproduce the original issue if it is changed to issue the GET request as follows:

      diff --git a/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java b/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java
      index 0ff21c23a8f..16b117b8a66 100644
      --- a/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java
      +++ b/test/jdk/java/net/httpclient/ContentLengthHeaderTest.java
      @@ -142,7 +142,7 @@ public void getWithNoBody(Version version, URI uri) throws IOException, Interrup
               testLog.println(version + " Checking GET with no request body");
               HttpRequest req = HttpRequest.newBuilder()
                       .version(version)
      - .GET()
      + .method("GET", HttpRequest.BodyPublishers.noBody())
                       .uri(uri)
                       .build();
               HttpResponse<String> resp = hc.send(req, HttpResponse.BodyHandlers.ofString(UTF_8));

      This ends up generating a request which has the following request headers:

      INFO: HEADERS: REQUEST HEADERS:
        GET /no_body HTTP/1.1
          Content-Length: 0
          Host: 127.0.0.1:12345
          User-Agent: Java-http-client/26-internal

      ### Why is this an HTTP/1.1-only problem?

      HTTP/2 and HTTP/3 implementations of `HttpClient` already add the `Content-Length` header iff it is greater than zero:

      https://github.com/openjdk/jdk/blob/4728f746a89ca7cb787b3d9969f09a80cc92f502/src/java.net.http/share/classes/jdk/internal/net/http/Stream.java#L906-L908
      https://github.com/openjdk/jdk/blob/4728f746a89ca7cb787b3d9969f09a80cc92f502/src/java.net.http/share/classes/jdk/internal/net/http/Http3ExchangeImpl.java#L388-L390

      They do this, unlike the `POST` and `PUT` exemption for HTTP/1.1 in the proposed PR, for all methods.
      This behavior difference between HTTP/1 and HTTP/{2,3} is not a problem because

      1. HTTP/2 and HTTP/3 are implicitly chunked when `Content-Length` is missing.
      2. `Content-Length` is always optional for HTTP/2 and HTTP/3, for all methods. A user agent may add it, in which case it must match the total number of bytes sent in the body request.

        There are no Sub-Tasks for this issue.

            djelinski Daniel Jelinski
            jpai Jaikiran Pai
            Votes:
            0 Vote for this issue
            Watchers:
            7 Start watching this issue

              Created:
              Updated:
              Resolved: