Guti
Guti

Reputation: 57

Java 11 HttpClient does not allow headers starting by colon

I am trying to send a POST request (HTTP/2) with a header called ":path" but looks like HttpClient in java 11 does not allow headers starting by colon.

This header should be fine using HTTP/2.

That is how my code looks like:

    HttpClient httpClient = HttpClient.newHttpClient();

    HttpRequest mainRequest = HttpRequest.newBuilder()
            .uri(URI.create("xxxx"))
            .setHeader(":method", "POST")
            .setHeader(":path", "xxxxx")
            .POST(HttpRequest.BodyPublishers.ofString(json))
            .build();

    HttpResponse<String> response = null;
    try {
        response = httpClient.send(mainRequest, HttpResponse.BodyHandlers.ofString());
    } catch (Exception e) {
        e.printStackTrace();
    }

Am I doing something wrong?

Upvotes: 0

Views: 823

Answers (1)

daniel
daniel

Reputation: 3278

Am I doing something wrong?

Yes. Pseudo header fields are generated by the HttpClient itself. You do not need to set :method or :path headers, the HttpClient will do it for you.

HttpRequest mainRequest = HttpRequest.newBuilder()
        .uri(URI.create("xxxx"))
        .POST(HttpRequest.BodyPublishers.ofString(json))
        .build();

is sufficient. :path and :method will be added as appropriate by the HttpClient if the request is transmitted over HTTP/2.

Upvotes: 4

Related Questions