Single Class Java HTTP Client with Proxy and SSL/TLS Keystore Settings

Sometimes this is useful for the diagnosis of configuration and network problems of ones Java application. This is our single-class HTTP client example without the need for external dependencies: HttpTest.java import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory; import java.io.FileInputStream; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ProxySelector; import java.net.URI; import java.net.URISyntaxException; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpRequest.BodyPublishers; import java.net.http.HttpResponse; import java.net.http.HttpResponse.BodyHandlers; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.time.Duration; import java.time.temporal.ChronoUnit; public class HttpTest { public static void main(String[] args) throws URISyntaxException, NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException, IOException, CertificateException { String bodyPayload = """ ourpayload, json, xml, ... """; String keyStorePath = "/opt/keystore.jks"; String keyStorePassword = "ABCDEFG"; String proxyHost = "ourproxy.proxy"; String uriString = "https://some-service/api"; int proxyPort = 8080; int timeoutInSeconds = 60; KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(new FileInputStream(keyStorePath), keyStorePassword.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("PKIX"); keyManagerFactory.init(keyStore, null); TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); // using same keystore for both trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); HttpClient client = HttpClient.newBuilder() .proxy( ProxySelector.of(new InetSocketAddress(proxyHost, proxyPort))) .sslContext(sslContext) .build(); URI uri = new URI(uriString); HttpRequest request = HttpRequest.newBuilder(uri) .POST(BodyPublishers.ofString(bodyPayload)) .timeout(Duration.of(timeoutInSeconds, ChronoUnit.SECONDS)) .build(); System.out.printf("Sending POST request to %s, timeout: %ds%n", uri, timeoutInSeconds); try { HttpResponse response = client.send(request, BodyHandlers.ofString()); System.out.println("Response received..."); System.out.printf("\tResponse-Status: %d%n", response.statusCode()); System.out.printf("\tResponse-Body: %s%n", response.body()); System.out.println("-------------------------------------%n"); } catch (IOException e) { System.err.printf("IOException caught: %s%n", e.getMessage()); e.printStackTrace(System.err); } catch (InterruptedException e) { System.err.printf("IOException caught: %s%n", e.getMessage()); e.printStackTrace(System.err); } } } ...

August 2, 2022 · 2 min · 253 words · Micha Kops

Analyzing Java Applications on the Fly with Arthas

Arthas created by Alibaba is a tool that allows developers to connect to running Java applications without stopping them or suspending threads for debugging the application from the console. It offers features like monitoring invocation statistics, searching for classes and methods in the classloaders, view method invocation details (like parameters), show the stack trace of a method invocation, monitor system metrics and others. In the following examples I’m going to demonstrate some of these features applied to a running web application. ...

October 31, 2018 · 8 min · 1525 words · Micha Kops

Finding Memory Leaks using Eclipse and the MemoryAnalyzer Plugin

The MemoryAnalyzer Plugin for Eclipse allows us to quickly analyze heap dumps from a virtual machine and search for memory leaks. In the following tutorial we’re going to create and run a small application that is going to cause an OutOfMemoryException during its runtime. In addition, we’re forcing the virtual machine to save a heap dump and finally analyzing this data using Eclipse and the MemoryAnalyzer plugin. Prerequisites Java Development Kit 6 Eclipse Indigo ...

November 2, 2011 · 4 min · 704 words · Micha Kops

Java Snippets

Remote Debug a Pod’s Java Process Simple steps for remote debugging a Java process running on a k8 pod: Edit deployment and add the following parameters to the Java start line: -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=127.0.0.1:5005 Also add the following port mapping at the section container → ports in the deployment: - containerPort: 5005 protocol: TCP Safe, wait for the new pods and then add a port forward for port 5005 for this pod: kubectl port-forward podname 5005 ...

March 1, 2010 · 13 min · 2583 words · Micha Kops

Spring Boot Snippets

Define and Configure Log Groups This allows to configure a group of loggers at the same time Define a log group named myaspect with two packages application.properties logging.group.myaspect=com.hascode.package1,com.hascode.package2 Configure the log group and set all loggers to level TRACE application.properties logging.level.myaspect=TRACE This is also possible as parameter on startup java -Dlogging.level.myaspect=TRACE myapp.jar Use JUnit 5 with Spring Boot Use newer versions of Surefire and Failsafe plugins: <properties> [..] <maven-failsafe-plugin.version>2.22.0</maven-failsafe-plugin.version> <maven-surefire-plugin.version>2.22.0</maven-surefire-plugin.version> </properties> ...

March 1, 2010 · 6 min · 1082 words · Micha Kops