1
I am building a Java application that consumes a REST Web Service. I sought to use the new Httpclient of Java 11. However, the same request in this target application sometimes gets a post, sometimes gets a GET but with the same head changing only the method.
In the examples I found on the Internet I invoke the Httprequest method and build it with . Method1(). Methodo2() and so on. So in my case of use as sometimes I have GET SOMETIMES POST but the header and URL are the same, I need to do the following:
private HttpResponse<String> getResponse() throws IOException, InterruptedException {
HttpRequest request;
if(post) {
request = HttpRequest.newBuilder()
.uri(URI.create(url))
.POST(HttpRequest.BodyPublishers.ofString(payload))
.header("Content-Type", "application/json")
.build();
} else {
request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.header("Content-Type", "application/json")
.build();
}
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
I’m doing an IF and having to repeat the same whole structure, I would have like to intervene in the middle of it with kind of a ternary to have only one method?
Important note: even if it is possible to use Httpclient / Httprequest otherwise I would like it to be preserved in this way even so that I can understand better, because it is not the first example of the genre I see, I’ve seen the same scenario in Twilio ML using this "Builder" to build XML, and there a same parameter can be repeated, example:
Message message = new Message.Builder().body(body).body(body1).media(media).build();
What if I wanted to repeat N times in the case of Twilio? How would I?
It has a name for this method chain structure?
Piovezan thanks for the quick reply. It is well aligned with what I am waiting for, now with the name of Pattern I am already researching on the subject to specialize more. But there is still a doubt, using the same example you gave, if I know the amount of header only during execution, as I would add several . header (according to demand). Starting from the premise that there is no . headers method (with s at the end) in this example. How to encapsulate this in my class since there is no ternary for this?
– soterocra
I edited the answer.
– Piovezan
Thanks! Guided me a lot with respect to the Builder :D pattern
– soterocra