Skip to content

Instantly share code, notes, and snippets.

@jscott7
Last active December 1, 2019 20:43
Java Rest Client supporting SSL and self-signed certificate
protected String getData(String... params)
{
// Removed params checks
try
{
if (!params[0].isEmpty())
{
m_restUrl += "?date=" + params[0];
}
URL url = new URL(m_restUrl);
SSLContext sslContext = getSSLContext();
HttpsURLConnection urlConnection = (HttpsURLConnection)url.openConnection();
urlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
try (ByteArrayOutputStream result = new ByteArrayOutputStream())
{
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) != -1)
{
result.write(buffer, 0, length);
}
output = result.toString("UTF-8");
} finally
{
urlConnection.disconnect();
}
} catch (Exception ex)
{
output = "ERROR: " + ex.getMessage();
}
return output;
}
/**
* If we aren't using a public CA for the SSL connection we can trust the self-signed CA
* @return SSLContext that includes self-signed CA
*/
private SSLContext getSSLContext()
{
try {
CertificateFactory cf = CertificateFactory.getInstance("X.509");
// Load the CA. I've included in the Assets folder
AssetManager assetManager = m_context.getAssets();
InputStream caInput = assetManager.open("myCA.pem");
Certificate ca;
try
{
ca = cf.generateCertificate(caInput);
}
finally
{
caInput.close();
}
// Create a KeyStore containing our trusted CA
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", ca);
// Create a TrustManager that trusts the CAs in our KeyStore
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
tmf.init(keyStore);
// Create an SSLContext that uses our TrustManager
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, tmf.getTrustManagers(), null);
return context;
}
catch(Exception ex)
{
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment