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.
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:
This example demonstrates basic HTTP client functionality in Java. The java.net.http
package offers many more features for more complex HTTP operations.