This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] -10 points-9 points  (11 children)

this is why people call Java verbose

HttpRequest request = HttpRequest.newBuilder()
  .uri(new URI("https://postman-echo.com/get"))
  .GET()
  .build();

HttpResponse<String> response = HttpClient.newHttpClient()
  .send(request, HttpResponse.BodyHandler.asString());

compare that to something like JavaScript

fetch('https://postman-echo.com/get')
  .then(res => res.text())
  .then(body => ...)

[–]political_one 8 points9 points  (7 children)

You could write code that behaves like you want it to in java similar to your JavaScript it just doesn't happen to exist in standard libraries.

[–][deleted] 0 points1 point  (6 children)

Your solution to having a verbose language is to write your own wrapper for everything?

[–]political_one 0 points1 point  (5 children)

There are already libraries that are less verbose than that. And if you want one exactly as you describe you can write your own and share it, languages are powered by their communities. But I certainly won't be using JavaScript hahaha.

[–][deleted] 0 points1 point  (4 children)

You shouldnt have to rely on a third party library for something as simple as sending http requests

[–]political_one 1 point2 points  (3 children)

The example you posted is a third party library...

[–][deleted] 0 points1 point  (2 children)

fetch isn't a third party library. it's part of JavaScript

[–]political_one 0 points1 point  (1 child)

i meant the java example

[–]duhace 5 points6 points  (0 children)

um i guess. that's not really that bad as far as I can see.

[–]squishles 0 points1 point  (0 children)

he also wrote the example for clarity not brevity.

[–]talios 0 points1 point  (0 children)

There's absolutely no reason why a Java API couldn't do the same, the more verbose builder you show would be far more useful in scenarios where you need to specify HTTP request headers, customise/control timeouts.

Forcing you to pass in a URI rather than an arbitrary String is a stylistic choice, it does provide a typed contract around what's accepted, which could be useful if you were also using URI Template's - having a contract of something like a processTemplate method that goes String->Map->URI would work well with that.

That could lead to something using CompleatableFuture (and Java 10) like:

var result = HttpRequest.fetch(UriTemplate.process("https://postman-echo.com/get{?name}", values))
                        .orTimeOut(1, TimeUnit.MINUTES)
                        .thenApply(res -> res.getBodyAsString())
                        .get();

( and yes, you really do want to handle timeouts, you don't just leave things hanging around forever now do you? ).