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

Fast Link Checks using Filiph Linkchecker and Docker

This Linkchecker claims to be way faster than blc and wummel/linkchecker. Using Docker, we may validate our site’s links in no time and without complex setup. docker run --rm tennox/linkcheck hascode.io Resources https://github.com/filiph/linkcheck

May 2, 2022 · 1 min · 33 words · Micha Kops

Testing Java Applications for Resilience by Simulating Network Problems with Toxiproxy, JUnit and the Docker Maven Plugin

When implementing distributed systems, client-server architectures and simple applications with network related functionalities, everything is fine when we’re in the development or in the testing stage because the network is reliable and the communicating systems are not as stressed as they are in production. But to sleep well we want to validate how resilient we have implemented our systems, how they behave when the network fails, the latency rises, the bandwidth is limited, connections time out and so on. ...

July 29, 2018 · 9 min · 1836 words · Micha Kops

AWS Snippets

Install AWS CLI v2 $ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.0.30.zip" -o "awscliv2.zip" unzip awscliv2.zip sudo ./aws/install AWS Documentation Generate Signed URLs with Linux Tools e.g. for accessing a website behind a CloudFront distribution using a canned policy. Write the policy file policy { "Statement": [ { "Resource": "https://xxxxxxxxxxxx.cloudfront.net/", "Condition": { "DateLessThan": { "AWS:EpochTime": 1648293147 } } } ] } Then apply the following commands[1] - you need to have OpenSSL installed. cat policy | tr -d "\n" | (1) tr -d " \t\n\r" | (2) openssl sha1 -sign private_key.pem | (3) openssl base64 -A | (4) tr -- '+=/' '-_~' (5) ...

March 1, 2018 · 2 min · 371 words · Micha Kops

Writing BDD-Style Webservice Tests with Karate and Java

There is a new testing framework out there called Karate that is build on top of the popular Cucumber framework. Karate makes it easy to script interactions with out web-services under test and verify the results. In addition it offers us a lot of useful features like parallelization, script/feature re-use, data-tables, JsonPath and XPath support, gherkin syntax, switchable staging-configurations and many others. In the following tutorial we’ll be writing different scenarios and features for a real-world RESTful web-service to demonstrate some of its features. ...

April 6, 2017 · 12 min · 2549 words · Micha Kops

Writing a Websocket Chat in Go

Learning the Go programming language, I wanted to implement an application that I had written with other languages and frameworks before to get a grip on this language. That’s why I tried to implement a really simple websocket chat server in Go and described my approach in the following article. Go Websocket Chat Implementation Writing the Chat Server Websocket Chat in Action ...

October 29, 2016 · 6 min · 1123 words · Micha Kops

Creating Microservices with Bootique

When it comes to writing microservices in Java, plenty of tools and frameworks exist. In the following tutorial, I’d like to demonstrate another minimalistic framework called Bootique by implementing a simple microservice exposing its functions either as a RESTful web-service or as a runnable command executed using the command line. Bootique Command Line Dependencies Using Maven here, we’re adding the following elements to our project’s pom.xml: Bootiques Bill of Materials as dependency management: bootique-bom Bootique Jersey for our REST service: bootique-jersey Bootique Logback for logging: bootique-logback Maven Shade Plugin to assemble our fat-jar ...

September 18, 2016 · 6 min · 1070 words · Micha Kops

Mocking HTTP Interaction with Java, JUnit and MockServer

When writing tests for our software components sometimes we need to mock external services based on the HTTP protocol, might it be a RESTful web-service, an XML-RPC call or a simple GET request to some web-server. In the following short tutorial I’d like to demonstrate how to create a mock HTTP server for testing and how to bootstrap and bind it to the life-cycle of a classical build-management tool like Maven. ...

January 5, 2016 · 4 min · 821 words · Micha Kops

IntelliJ Snippets

Live Templates JUnit 5 Test @org.junit.jupiter.api.Test @org.junit.jupiter.api.DisplayName("$NAME$") void $METHOD$() throws Exception { $END$ } Figure 1. IntelliJ Live Template Editor Edit Variables: NAME METHOD: default-value camelCase(NAME) Figure 2. Editing template variables SLF4J Logger Template private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger( $CLASS$.class ); Edit variables: CLASS: expression: className() Favorite Shortcuts Select whole block in Editor Cmd+Tab+Down Select similar blocks in editor Ctrl+G Copy the absolute Path of the current File into Clipboard Cmd+Shift+C ...

March 1, 2010 · 2 min · 341 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