|
| 1 | +import java.net.URI; |
| 2 | +import java.net.http.HttpClient; |
| 3 | +import java.net.http.HttpRequest; |
| 4 | +import java.net.http.HttpResponse; |
| 5 | + |
| 6 | +public class Http3ClientDemo { |
| 7 | + public static void main(String[] args) { |
| 8 | + try { |
| 9 | + var client = HttpClient.newBuilder() |
| 10 | + .version(HttpClient.Version.HTTP_3) // Enable HTTP/3 |
| 11 | + .build(); |
| 12 | + |
| 13 | + var request = HttpRequest.newBuilder() |
| 14 | + .uri(new URI("https://www.google.com")) // Any HTTPS site |
| 15 | + .GET() |
| 16 | + .build(); |
| 17 | + |
| 18 | + var response = client.send(request, HttpResponse.BodyHandlers.ofString()); |
| 19 | + |
| 20 | + System.out.println("Status Code: " + response.statusCode()); |
| 21 | + System.out.println("Response (first 200 chars):"); |
| 22 | + System.out.println(response.body().substring(0, 200)); |
| 23 | + |
| 24 | + } catch (Exception e) { |
| 25 | + e.printStackTrace(); |
| 26 | + } |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +/* |
| 31 | +What changed: Previous vs New |
| 32 | +
|
| 33 | +Previous Java style: |
| 34 | +- HttpClient used HTTP/1.1 or HTTP/2 |
| 35 | +- No native HTTP/3 support |
| 36 | +- Developers depended on external libraries for HTTP/3 |
| 37 | +
|
| 38 | +New Java 26 style: |
| 39 | +- Built-in HTTP/3 support in HttpClient |
| 40 | +- Just set version(HttpClient.Version.HTTP_3) |
| 41 | +- Cleaner and native implementation |
| 42 | +
|
| 43 | +Old approach example idea: |
| 44 | +var client = HttpClient.newBuilder() |
| 45 | + .version(HttpClient.Version.HTTP_2) |
| 46 | + .build(); |
| 47 | +
|
| 48 | +Why the new approach is better: |
| 49 | +- Faster communication (uses QUIC protocol) |
| 50 | +- Reduced latency |
| 51 | +- Better performance on unstable networks |
| 52 | +- No need for external libraries |
| 53 | +
|
| 54 | +Pros: |
| 55 | +1. Better performance |
| 56 | + - Faster than HTTP/2 in many cases |
| 57 | +
|
| 58 | +2. Reduced latency |
| 59 | + - Faster connection setup |
| 60 | +
|
| 61 | +3. Built-in support |
| 62 | + - No third-party dependency required |
| 63 | +
|
| 64 | +4. Modern networking |
| 65 | + - Uses QUIC (UDP-based) |
| 66 | +
|
| 67 | +Cons: |
| 68 | +1. Server dependency |
| 69 | + - Only works if server supports HTTP/3 |
| 70 | +
|
| 71 | +2. Fallback behavior |
| 72 | + - May fall back to HTTP/2 automatically |
| 73 | +
|
| 74 | +3. Debugging complexity |
| 75 | + - Harder to debug compared to HTTP/1.1 |
| 76 | +
|
| 77 | +Best use case: |
| 78 | +- High-performance web applications |
| 79 | +- APIs with low-latency requirements |
| 80 | +- Mobile or unstable network environments |
| 81 | +
|
| 82 | +Compile and run: |
| 83 | +javac Http3ClientDemo.java |
| 84 | +java Http3ClientDemo |
| 85 | +*/ |
0 commit comments