0

As I can see after Java 11 HttpURLRequest was substituted by HttpRequest.

How can I send a simple HTTP request using HttpRequest?

grutty
  • 11
  • Doesn't the JavaDoc on class `HttpRequest` help already? It basically tells you to use `HttpClient` and `HttpRequest.builder()`. – Thomas Nov 08 '21 at 10:37
  • I think you mean `HttpURLConnection`. It wasn't replaced. It is still available for applications to use as of Java 17. It hasn't been marked as deprecated. (As JEP 110 states: "This API is intended to **eventually** replace the` HttpURLConnection` API **for new code**...") – Stephen C Nov 08 '21 at 15:05
  • Does this answer your question? [How to send HTTP request in java?](https://stackoverflow.com/questions/1359689/how-to-send-http-request-in-java) – Mahozad Dec 31 '21 at 19:14

1 Answers1

2

A simple GET request using JDK 11 HttpClient + HttpRequest:

HttpClient client = HttpClient.newBuilder()
        .connectTimeout(Duration.ofSeconds(10))
        .build();

HttpRequest req = HttpRequest.newBuilder()
        .uri(URI.create("https://pathHere"))
        .GET().build();


client.send(req, HttpResponse.BodyHandlers.ofString()).body();
JCompetence
  • 6,997
  • 3
  • 19
  • 26