OKHttp is an easy to use http library with very few dependencies. It is also the provided library that loadcoder uses to generate loadtests.
Create the OKHttp client like this:
OkHttpClient client = new OkHttpClient();
Below shows how to create and send a request, with HTTP verb, body and headers set.
RequestBody body = RequestBody.create(MediaType.get("application/x-www-form-urlencoded; charset=UTF-8"), "http body");
Request req = new Request.Builder().url("https://localhost:8080/")
.method("POST", body)
.header("accept", "*/*")
.build();
Response resp = client.newCall(req).execute();
OkhttpClient will default follow redirects (HTTP 302). If you wish to disable this, you can do this by using the Builer methods below with the parameter false
OkHttpClient client = new OkHttpClient.Builder()
.followSslRedirects(false)
.followRedirects(false)
.build
If you want to call an endpoint over TLS, you need to create the RestTemplate so that it accepts the server certificate. There are a number of ways to do this.
The server certificate can be added as trusted by importing it into the Java cacerts. If the tests will execute at several machines, this may be an ardouous approach.
$ keytool -import -trustcacerts -keystore $JAVA_HOME/jre/lib/security/cacerts -storepass changeit -alias ServerToBeTested -import -file servercert.cer
You can create the OkHttpClient with a customized SSLContext and a HostnameVerifier. You can write your own logic which certificates to accept. Below example has a HostnameVerifier that always returns true, meaning that everything is accepted. Keep in mind that always accepting everything is less secure. Therefore, use this approach with caution.
public OkHttpClient createClient() {
try {
X509TrustManager manager = getX509TrustManager();
SSLContext sslContext = SSLContextBuilder
.create().build();
sslContext.init(null, new TrustManager[] { manager }, null);
SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
OkHttpClient client = new OkHttpClient.Builder().sslSocketFactory(sslSocketFactory, manager)
.hostnameVerifier((hostname, session)-> true)
.build();
return client;
}catch(Exception e) {
throw new RuntimeException(e);
}
}
private X509TrustManager getX509TrustManager() {
X509TrustManager manager = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
X509Certificate[] cArrr = new X509Certificate[0];
return cArrr;
}
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}
};
return manager;
}
Here are the Maven dependencies you need to use OKHttp as the client library for your load tests
com.squareup.okhttp3
okhttp-tls
4.2.2