Issue
I am trying to make an HTTP get request with SSL to check if the connection to a distant server is working, I found several examples on internet but none is entirely parsing, it seems that java is constantly changing and deprecating and removing old classes and methods.
Here is the maximum parsing code that I could obtain (some lines are still not parsing) :
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
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 javax.net.ssl.SSLContext;
import org.apache.http.ssl.SSLContexts;
//import org.apache.http.conn.ssl.SSLContexts;
public class SSLContextLoader {
public static SSLContext initSSLContext () {
String clientKeyStorePath = ConfigManager.GetInstance().GetKeyStorePath();
String trustStorePath = ConfigManager.GetInstance().GetTrustStorePath();
String clientKeyStorePassword = ConfigManager.GetInstance().GetKeyStorePassword();
String trustStorePassword = ConfigManager.GetInstance().GetTrustStorePassword();
String keyPassword = clientKeyStorePassword;
try {
final KeyStore clientKeystore = KeyStore.getInstance("JKS");
clientKeystore.load(new FileInputStream(clientKeyStorePath), clientKeyStorePassword.toCharArray());
final KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());
final SSLContext sslContext = SSLContexts.custom()
.loadTrustMaterial(trustStore, null)
.loadKeyMaterial(clientKeystore, keyPassword.toCharArray())
.build();
return sslContext;
} catch (KeyStoreException e) {
e.printStackTrace();
} catch (CertificateException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (KeyManagementException e) {
e.printStackTrace();
}
return null;
}
}
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
public class GetRequest {
private final static String ENDPOINT_URL = "https://www.google.com/";
public void sendSSLRequest() {
final SSLContext sslContext = SSLContextLoader.initSSLContext();
final HttpClientBuilder clientbuilder = HttpClients.custom().setSslcontext(sslContext);
final HttpClient client = clientbuilder.build();
//final HttpGet request = new HttpGet(ENDPOINT_URL);
// HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://www.google.com/"))
.build();
//HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); // cannot find symbols httpClient and BodyHandlers
try {
// the following code needs a cast to (HttpUriRequest) to parse :
client.execute(request); // expecting (HttpUriRequest) and we have HttpRequest
} catch (final IOException e) {
//do some exception handling...
}
}
}
The httpClient.send is not parsing, because httpClient is not found.
Also client.execute(request); is not parsing because the builder returns an HttpRequest and the execute method expects HttpUriRequest which is a subclass.
send and execute are two alternatives (maybe working in different versions of libraries) to send the request and both not parsing.
here is my two maven dependencies for the apache libraries:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.3.5</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.8</version>
</dependency>
Solution
You need to generate HttpUriRequest differently as its interface so you have to use its implementation classes to create its object and pass it to execute method. Also
The method setSslcontext(SSLContext) from the type HttpClientBuilder is deprecated
so you should use SSLConnectionSocketFactory.
Without proxy
public void sendSSLRequest() {
final SSLContext sslContext = SSLContextLoader.initSSLContext();
final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
final CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpUriRequest request = new HttpGet(URI.create("https://www.google.com/"));
try {
client.execute(request);
} catch (final IOException e) {
// do some exception handling...
}
}
With proxy and without authentication
public void sendSSLRequest() {
HttpHost proxy = new HttpHost("ip address", 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
final SSLContext sslContext = SSLContextLoader.initSSLContext();
final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
final CloseableHttpClient client =
HttpClients.custom().setSSLSocketFactory(csf).setRoutePlanner(routePlanner).build();
HttpUriRequest request = new HttpGet(URI.create("https://www.google.com/"));
try {
client.execute(request);
} catch (final IOException e) {
// do some exception handling...
}
}
With proxy with authentication
public void sendSSLRequest() {
HttpHost proxy = new HttpHost("ip address", 8080);
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
// Client credentials
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(new AuthScope(proxy),
new UsernamePasswordCredentials("username_admin", "secret_password"));
// Create AuthCache instance
AuthCache authCache = new BasicAuthCache();
BasicScheme basicAuth = new BasicScheme();
authCache.put(proxy, basicAuth);
HttpClientContext context = HttpClientContext.create();
context.setCredentialsProvider(credentialsProvider);
context.setAuthCache(authCache);
final SSLContext sslContext = SSLContextLoader.initSSLContext();
final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
final CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(csf).setRoutePlanner(routePlanner)
.setDefaultCredentialsProvider(credentialsProvider).build();
HttpUriRequest request = new HttpGet(URI.create("https://www.google.com/"));
try {
client.execute(request, context);
} catch (final IOException e) {
// do some exception handling...
}
}
Answered By - Dhaval Gajjar
Answer Checked By - Mildred Charles (JavaFixing Admin)