Http Client in Fortress

Here’s the translation of the Go HTTP Client example to Java, formatted in Markdown suitable for Hugo:

Our example demonstrates how to create a simple HTTP client using Java’s built-in java.net.http package. This package provides excellent support for HTTP clients and servers.

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.io.IOException;
import java.util.Scanner;

public class HttpClientExample {
    public static void main(String[] args) {
        try {
            // Create an HttpClient object
            HttpClient client = HttpClient.newHttpClient();

            // Create an HttpRequest object for a GET request
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create("https://gobyexample.com"))
                    .build();

            // Send the request and get the response
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

            // Print the HTTP response status
            System.out.println("Response status: " + response.statusCode());

            // Print the first 5 lines of the response body
            Scanner scanner = new Scanner(response.body());
            for (int i = 0; i < 5 && scanner.hasNextLine(); i++) {
                System.out.println(scanner.nextLine());
            }
            scanner.close();

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

In this example, we use the HttpClient class to send an HTTP GET request to a server. The HttpClient.newHttpClient() method creates a new client with default settings.

We create an HttpRequest object using the HttpRequest.newBuilder() method, specifying the URL we want to request.

We then send the request using the client.send() method, which returns an HttpResponse object. We use HttpResponse.BodyHandlers.ofString() to handle the response body as a string.

After receiving the response, we print the HTTP status code.

To print the first 5 lines of the response body, we use a Scanner to read the response body line by line. We limit the output to 5 lines or less if the response body is shorter.

To run this program, save it as HttpClientExample.java and use the following commands:

$ javac HttpClientExample.java
$ java HttpClientExample
Response status: 200
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Go by Example</title>

This example demonstrates basic HTTP client functionality in Java. The java.net.http package offers many more features for more complex HTTP operations.