I'm building a server that has to call two webservices. Webservices have the same CA certificate (PKCS12).
the first one receives request by GET, the other one by SOAP call.
follow a part of code that creates connection for GET request
InputStream inputStream = null;
// is https protocol?
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
// create connection
HttpsURLConnection httpsUrlConnection = null;
if(proxy != null){
httpsUrlConnection = (HttpsURLConnection) url.openConnection(proxy);
} else {
httpsUrlConnection = (HttpsURLConnection) url.openConnection();
}
// set the check to: do not verify
httpsUrlConnection.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
setHeaders(httpsUrlConnection, headers);
//set del certificato
log.debug("set certificate for get...");
File cerp12 = new File(Utils.getWebAppLocalPath(),"WEB-INF"+String.valueOf(File.separatorChar)+PropConfig.getProperty("cer.p12"));
((HttpsURLConnection) httpsUrlConnection).setSSLSocketFactory(security(cerp12,PropConfig.getProperty("cer.pwd")));
httpsUrlConnection.connect();
inputStream = httpsUrlConnection.getInputStream();
} else {
HttpURLConnection httpUrlConnection = null;
if(proxy != null){
httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
} else {
httpUrlConnection = (HttpURLConnection) url.openConnection();
}
setHeaders(httpUrlConnection, headers);
inputStream = httpUrlConnection.getInputStream();
}
in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
and this part is for SOAP request
InputStream inputStream = null;
// is https protocol?
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
// create connection
HttpsURLConnection httpsUrlConnection = null;
if(proxy != null){
httpsUrlConnection = (HttpsURLConnection) url.openConnection(proxy);
} else {
httpsUrlConnection = (HttpsURLConnection) url.openConnection();
}
// set the check to: do not verify
httpsUrlConnection.setHostnameVerifier(new HostnameVerifier() {
#Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
setHeaders(httpsUrlConnection, headers);
//set del certificato
log.debug("set certificate for get...");
File cerp12 = new File(Utils.getWebAppLocalPath(),"WEB-INF"+String.valueOf(File.separatorChar)+PropConfig.getProperty("cer.p12"));
((HttpsURLConnection) httpsUrlConnection).setSSLSocketFactory(security(cerp12,PropConfig.getProperty("cer.pwd")));
httpsUrlConnection.connect();
inputStream = httpsUrlConnection.getInputStream();
} else {
HttpURLConnection httpUrlConnection = null;
if(proxy != null){
httpUrlConnection = (HttpURLConnection) url.openConnection(proxy);
} else {
httpUrlConnection = (HttpURLConnection) url.openConnection();
}
setHeaders(httpUrlConnection, headers);
inputStream = httpUrlConnection.getInputStream();
}
in = new BufferedReader(new InputStreamReader(inputStream));
String inputLine;
while ((inputLine = in.readLine()) != null) {
result.append(inputLine);
}
the code is almost the same
with GET request I have no problem, but with SOAP request httpsUrlConnection.connect(); throws
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
Here is howto create ssl context for HTTPS connection.
SSLSocketFactory socketFactory = createSSLContext().getSocketFactory();
HttpsURLConnection connection = (HttpsURLConnection) (url).openConnection();
connection.setSSLSocketFactory(socketFactory);
And method to create SSL context. Note, it load root server certificate from .pem file (x509 format) and client certificate from .p12 (pkcs12 format). If server don't required client certificate, pass null for key managers. If server sertificate issued by authority, which already in $JRE_HOME/lib/security/cacerts, pass null as trust managers.
And one more note: in .pem file you should store root certificate in PKIX path of server certificate. For example, github.com That site has PKIX path CN = github.com -> CN = DigiCert High Assurance EV CA-1 -> CN = DigiCert High Assurance EV Root CA -> CN = GTE CyberTrust Global Root. So you store GTE CyberTrust Global Root
private final SSLContext createSSLContext()
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, IOException,
UnrecoverableKeyException, KeyManagementException {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(Config.getString(Config.KEYSTORE_PATH)));
} catch (Exception ex) {
throw new IOException("not found keystore file: " Config.getString(Config.KEYSTORE_PATH), ex);
}
try{
keyStore.load(fis, Config.getString(Config.KEYSTORE_PASSWORD).toCharArray());
}finally {
IOUtils.closeQuietly(fis);
}
CertificateFactory cf = CertificateFactory.getInstance("X.509");
FileInputStream in = new FileInputStream(Config.getString(Config.HTTPS_SERVER_CERT));
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(null);
try {
X509Certificate cacert = (X509Certificate) cf.generateCertificate(in);
trustStore.setCertificateEntry("alias", cacert);
} finally {
IOUtils.closeQuietly(in);
}
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
tmf.init(trustStore);
KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
kmf.init(keyStore, Config.getString(Config.KEYSTORE_PASSWORD).toCharArray());
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom());
return sslContext;
}
Related
I am creating an application where I want to POST xml data directly (without key value pair) to API. The API needs certification authentication which is done here in code. Now I want to POST the data to same URL.
Here is what I want to do :
My current code is :
#Override
public String demoAPI(String xmlData) {
StringBuilder sb = new StringBuilder();
String output="";
try {
KeyStore clientStore = KeyStore.getInstance("PKCS12");
clientStore.load(new FileInputStream(new File("path-to-pfx-file")),
"password".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, "password".toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("path-to-jks-file"), "password".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
TrustManager[] tms = tmf.getTrustManagers();
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(kms, tms, new SecureRandom());
SSLContext.setDefault(sslContext);
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
URL url = new URL("URL");
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setConnectTimeout(100000);
con.setSSLSocketFactory(sslContext.getSocketFactory());
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
System.out.println(sb.toString());
output = sb.toString();
} catch (Exception e) {
e.printStackTrace();
output = e.getMessage();
}
return output;
}
Whereas , for same url , I want to POST xmlData from method.
How can I do that ? What should I change in the code after
con.setRequestMethod("POST"); ?
You have a url and you have some XML to post this url via HTTP. And your post request is a SOAP request, you can send this soap message in the body of this request. So nothing special or different than many developers' do. Post your soap data via http by using java.net or Apache or others. Here are the code samples to do this:
HttpsURLConnection con = null;
try{
URL url = new URL("URL");
con = (HttpsURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("content-type", "application/x-www-form-urlencoded");
con.setRequestProperty("Content-Language", "application/soap+xml; charset=utf-8"); // request properties, set your needs
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(xmlData.getBytes("utf-8"));
os.close();
}catch(Exception e){
e.printStackTrace();
}finally{
con.disconnect();
}
Another option would be to use Apache library. And the code:
HttpPost httpPost = new HttpPost("URL");
StringEntity strEntity = new StringEntity(xmlData, "text/xml", "UTF-8");
strEntity.setContentType("text/xml");
httpPost.setHeader("Content-Type","application/soap+xml;charset=UTF-8");
httpPost.setEntity(strEntity);
HttpClient httpclient = new DefaultHttpClient();
BasicHttpResponse httpResponse = (BasicHttpResponse) httpclient.execute(httpPost);
I want to add TLS 1.2 to the below code, Tried by creating socket but no luck. Can someone help on it ? Can we add it after creating a client ?
private static int executeSOAPRequest(String req, String targetURL)
throws Exception {
PostMethod post = new PostMethod(targetURL);
post.setRequestBody(req);
post.setRequestHeader("Content-type",
"text/xml; characterset=ISO-8859-1");
post.setRequestHeader("SOAPAction", "\"\"");
// prepare HTTP Client
HttpClient client = new HttpClient();
client.getParams().setParameter("SOAPAction", "\"\"");
// Post the request
int respCode = client.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
// If response is not success
if (respCode != 200)
throw new Exception("Executing SOAP request has failed.");
// Convert the response into NOM XML
int resp = 0;
Document doc = nomDocPool.lendDocument();
try {
resp = doc.parseString(post.getResponseBodyAsString());
nomDocPool.returnDocument(doc);
} catch (XMLException e) {
nomDocPool.returnDocument(doc);
//logger.error("Exception while generating SAML : "
//+ e);
throw e;
}
System.out.println("resp: "+resp);
return resp;
}
HttpClient already handles TLS for you. This is documented:
http://hc.apache.org/httpclient-3.x/sslguide.html
HttpClient provides full support for HTTP over Secure Sockets Layer (SSL) or IETF Transport Layer Security (TLS) protocols by leveraging the Java Secure Socket Extension (JSSE). JSSE has been integrated into the Java 2 platform as of version 1.4 and works with HttpClient out of the box.
All you have to do is make sure your targetURL is using https:// instead of http://, then HttpClient handles the rest for you.
Forget HttpClient. Use javax.net.ssl.HttpsURLConnection.
String myResponse = null;
URL url = new URL(targetURL);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.setRequestProperty("Content-Type", "text/xml; characterset=ISO-8859-1");
con.setRequestProperty("SOAPAction", "\"\"");
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setSSLSocketFactory(My_Lovely_CertificateHelper.getSslSocketFactory());
con.connect();
OutputStream os = con.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "ISO-8859-1");
osw.write(req);
osw.flush();
osw.close();
InputStream is = null;
if (con.getResponseCode() < HttpsURLConnection.HTTP_BAD_REQUEST) {
is = con.getInputStream();
} else {
is = con.getErrorStream();
}
InputStreamReader isr = new InputStreamReader(is, "ISO-8859-1");
int read = -1;
char[] buff = new char[1024];
StringBuilder sb = new StringBuilder();
while ((read = isr.read(buff)) != -1) {
sb.append(buff, 0, read);
}
myResponse = sb.toString();
return myResponse;
getSslSocketFactory()
public static SSLSocketFactory getSslSocketFactory() throws Exception {
SSLContext sc = SSLContext.getInstance("TLSv1.2");
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
String trustStorePath = getcertPath(); //"user.dir" + "\ohHappyDays.jks";
String password = "finallyFoundLoveIn2021";
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream(trustStorePath), password.toCharArray());
kmf.init(ks, password.toCharArray());
sc.init(kmf.getKeyManagers(), (TrustManager[]) null, (SecureRandom) null);
return sc.getSocketFactory();
}
I am writing a web service using Jersey and Grizzly. I want to run it using SSL. I have created server.jks and client.jks just like described here.
Running the web service:
public static HttpServer startServer() {
final ResourceConfig rc = new ResourceConfig().packages("com.mypackage");
SSLContextConfigurator sslContextConfigurator = new SSLContextConfigurator();
sslContextConfigurator.setKeyStoreFile("server.jks");
sslContextConfigurator.setKeyStorePass("changeit");
SSLEngineConfigurator sslEngineConfigurator = new SSLEngineConfigurator(sslContextConfigurator);
return GrizzlyHttpServerFactory.createHttpServer(URI.create(getURI().toString()), rc, true,
sslEngineConfigurator);
}
private static URI getURI() {
URI uri;
// Running on localhost
uri = UriBuilder.fromUri("https://" + "localhost/" + ConstApp.APP_PATH).port(ConstApp.PORT)
.build();
return uri;
}
So running the web service on localhost port 443 with the server.jks.
Now I want to check and test the web service.
Java HTTPClient class:
String https_url = "https://localhost:443/myapp";
URL url;
try {
url = new URL(https_url);
HttpsURLConnection sslCon = (HttpsURLConnection) url.openConnection();
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
FileInputStream stream = new FileInputStream("client.jks");
keyStore.load(stream, "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keyStore);
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tmf.getTrustManagers(), null);
SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();
sslCon.setSSLSocketFactory(sslSocketFactory);
sslCon.setRequestMethod("GET");
// add request header
sslCon.setRequestProperty("User-Agent", "Mozilla/5.0");
int responseCode = sslCon.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(sslCon.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
Running the HTTPClient result in an exception:
javax.net.ssl.SSLProtocolException: Handshake message sequence violation, 1
at sun.security.ssl.ClientHandshaker.processMessage(ClientHandshaker.java:196)
at sun.security.ssl.Handshaker.processLoop(Handshaker.java:979)
at sun.security.ssl.Handshaker.process_record(Handshaker.java:914)
at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1062)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1375)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1513)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1441)
at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:480)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:338)
at httpClient.HTTPClient.testIt(HTTPClient.java:158)
at httpClient.HTTPClient.main(HTTPClient.java:36)
Can anyone please help me out here and tell me what am I doing wrong?
I would like to connect to a test server in https from a java program I made. I don't want to verify anything in the certificate, how can I achieve this?
I am using:
HttpURLConnection connection = (HttpURLConnection) ( new URL(server).openConnection() );
connection.setDoOutput (true);
connection.setDoInput (true);
connection.setInstanceFollowRedirects(false);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
OutputStreamWriter wout = new OutputStreamWriter(out, "UTF-8");
wout.write(xml);
wout.flush();
out .close();
//READ RESPONSE.
InputStream in = connection.getInputStream();
But when I execute, I get:
javax.net.ssl.SSLHandshakeException: java.security.cert.CertificateException: No subject alternative names present
Generally you can acces https sites but Somesites wanted the certificate. So you can use under the codes. And you have to take certificate with InstallCert program.
String httpsURL = "https://www.google.com";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
You can do that this way..
URL url1;
try {
url1 = new URL(url);
if(url1.getProtocol().equalsIgnoreCase("https")){// you dont need this check
try {
HostnameVerifier hv = new HostnameVerifier() {
public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) {
if (urlHostName.equals(session.getPeerHost())) {
logger.info("Verified HTTPS "+session.getPeerHost()+" >> "+ urlHostName);
} else {
logger.info("Warning: URL host "+urlHostName+" is different to SSLSession host "+session.getPeerHost());
}
return true;
}
};
TrustManager[] trustAll = new javax.net.ssl.TrustManager[] { new javax.net.ssl.X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
}
} };
javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL");
sc.init(null, trustAll, new java.security.SecureRandom());
SSLSocketFactory factory = (SSLSocketFactory) sc.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(factory);
HttpsURLConnection.setDefaultHostnameVerifier(hv);
HttpsURLConnection connection = (HttpsURLConnection) url1.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
Continue with your OutputStreamWriter write part.
You can do this without importing ssl certificate and without any third party support.
if you're trying to get from https://IP/file, it'll return the error the IP is not verified
I have 2 apps, one is a Servlet/Tomcat Server, and the other is an Android app.
I want to use HttpURLConnection to send and receive XML between both.
Code:
private String sendPostRequest(String requeststring) {
DataInputStream dis = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection urlConnection = null;
try {
URL url = new URL(this.getServerURL());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
out.write(requeststring.getBytes());
out.flush();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
dis = new DataInputStream(in);
int ch;
long len = urlConnection.getContentLength();
if (len != -1) {
for (int i = 0; i < len; i++)
if ((ch = dis.read()) != -1) {
messagebuffer.append((char) ch);
}
} else {
while ((ch = dis.read()) != -1)
messagebuffer.append((char) ch);
}
dis.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
urlConnection.disconnect();
}
return messagebuffer.toString();
}
Now, I need to use SSL to send the XMLs for security.
First, I use Java Keytool to generate the .keystore file.
Keytool -keygen -alias tomcat -keyalg RSA
Then I put the XML Code on server.xml file of Tomcat to use SSL
<Connector
port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
keystoreFile="c:/Documents and Settings/MyUser/.keystore"
keystorePass="password"
clientAuth="false" sslProtocol="TLS"
/>
Then, I change it the HttpURLConnection for HttpsURLConnection
private String sendPostRequest(String requeststring) {
DataInputStream dis = null;
StringBuffer messagebuffer = new StringBuffer();
HttpURLConnection urlConnection = null;
//Conexion por HTTPS
HttpsURLConnection urlHttpsConnection = null;
try {
URL url = new URL(this.getServerURL());
//urlConnection = (HttpURLConnection) url.openConnection();
//Si necesito usar HTTPS
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
//Creo la Conexion
urlHttpsConnection = (HttpsURLConnection) url.openConnection();
//Seteo la verificacion para que NO verifique nada!!
urlHttpsConnection.setHostnameVerifier(DO_NOT_VERIFY);
//Asigno a la otra variable para usar simpre la mism
urlConnection = urlHttpsConnection;
} else {
urlConnection = (HttpURLConnection) url.openConnection();
}
//Do the same like up
and add a trustAllHosts method to Trust every server (dont check for any certificate)
private static void trustAllHosts() {
X509TrustManager easyTrustManager = new X509TrustManager() {
public void checkClientTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
// Oh, I am easy!
}
public void checkServerTrusted(
X509Certificate[] chain,
String authType) throws CertificateException {
// Oh, I am easy!
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {easyTrustManager};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
e.printStackTrace();
}
}
Those changes worked very good, but I don´t want to Trust every server. I want to use my keystore file to validate the connection and use SSL in the right way.
I read a lot on the internet and made a lot of tests, but I can´t understand what I have to do and how to do it.
Can somebody help me?
Thank you very much
Sorry for my poor english
-------------------------UPDATE 2011/08/24-------------------------------------------------
Well, I'm still working on this. I made a new method to set the KeyStore, InputStream, etc
The method looks like this:
private static void trustIFNetServer() {
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("BKS");
InputStream in = context.getResources().openRawResource(R.raw.mykeystore);
String keyPassword = "password";
ks.load(in, keyPassword.toCharArray());
in.close();
tmf.init(ks);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, tms, new java.security.SecureRandom());
} catch (Exception e) {
e.printStackTrace();
}
}
First I had a lot of problems with the Key and the Certificate, but now it is working (I think so)
My problem right now is a TimeOut Exception. I don´t know why it is generated. I'm think it's something with the data write, but I can't solve yet.
Any Idea?
You need to create a trust store file for your self-signed certificate as described here.
Use it on the client side to connect with your server. It doesn't really matter if you use JKS or another format, I'll assume JKS for now.
To accomplish what you have in mind you need a different TrustManager, obviously. You can use TrustManagerFactory and feed its trust settings with your newly created trust store.
TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream in = new FileInputStream("<path to your key store>");
ks.load(in, "password".toCharArray());
in.close();
tmf.init(ks);
TrustManager[] tms = tmf.getTrustManagers();
Use tms to init your SSLContextinstead for the new trust settings to be used for your SSL/TLS connection.
Also you should make sure that the CN part of the server TLS certificate is equal to the FQDN (fully qualified domain name) of your server, e.g. if your server base URL is 'https://www.example.com', then the CN of the certificate should be 'www.example.com'. This is needed for host name verification, a feature that prevents man-in-the-middle-attacks. You could disable this, but only when using this your connection will be really secure.
Create your trust store, store at as an asset and use it initialize this SocketFactory. Then use the factory instead of your own 'trust everybody' one.
If you want to ignore all the certificate, ignore the handshake, then this works:
HttpsURLConnection and intermittent connections