How to execute a Unirest request after initialization

832 Views Asked by At

So I am working with a REST API in java. I got my POST request to work, but my code seems a bit inefficient to me, for example:

    HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post")
              .header("accept", "application/json")
              .queryString("apiKey", "123")
              .field("parameter", "value")
              .field("foo", "bar")
              .asJson();
    HttpResponse<JsonNode> jsonResponse2 = Unirest.post("http://httpbin.org/post")
              .header("accept", "application/json")
              .header("accept1", "application/json")
              .header("accept2", "application/json")
              .header("accept3", "application/json")
              .asJson();

I have two post requests. However, one of them has 4 headers. I was thinking of creating an utility class where I could just pass a HashMap of headers with their respective values. However, I can't do this because the only way I know on how to add a header is during the initialization of the jsonResponse. How can I add the headers after initializing the variable? Or how can I add the headers in an array or hashmap.

1

There are 1 best solutions below

0
On BEST ANSWER

You can use the .headers(Map<String, String> headers) method to add headers from a map, rather than repeating the header call, so you don't need the utility method.