1

I would like to add multiple headers to a java HTTP request, I think this is possible using the headers() method in the httpRequest builder, but I can't seem to figure out how:

 HttpRequest request = HttpRequest.newBuilder()
            .POST()
            .headers(/*add mutple headers here*/)
            .uri(getUrl())
            .build();
2

2 Answers 2

4

You can add multiple headers by invoking header(String,String) multiple times...

HttpRequest request2 = HttpRequest.newBuilder()
  .header("key1", "value1")
  .header("key2", "value2")
  ... stuff ...
  .build();

.. or you may use the varargs headers(String...) methods

HttpRequest request = HttpRequest.newBuilder()
  .headers("key1", "value1", "key2", "value2")
  ... stuff ...
  .build();
Sign up to request clarification or add additional context in comments.

Comments

2

The method headers allow you to pass a single key/value or a list of key/value https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpRequest.Builder.html#headers(java.lang.String...).

 HttpRequest request = HttpRequest.newBuilder()
            .POST()
            .headers("key1", "value1", "key2", "value2", "key3", "value3")
            .uri(getUrl())
            .build();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.