How to set up a Https connection with a Java application

I use java to create a desktop application, and this application uses the API. To provide connectivity with the API, I was informed of their support for using HTTPS. Let me know how to configure https connection with java client.

The API has this function, which states that it can choose a secure connection:

private String getUrlAddress(XmlRequest request) { // determine if this is a secure connection String url = this.ssl ? "https://" : "http://"; // determine service endpoint based on type of class/request passed in if( request.getClass() == MessageRequest.class) { url += ClockWorkSmsService.SMS_URL; } else { url += ClockWorkSmsService.CREDIT_URL; } return url; } 

this code gives me an idea that the β€œrequest” will be my current url or server, so I will configure an https connection on my side.

Clockworksms Toolbars:

 import com.clockworksms.*; public class DemoSms { public static void main(String[] args) { try { ClockWorkSmsService clockWorkSmsService = new ClockWorkSmsService("apikey"); SMS sms = new SMS("441234567890", "Hello World"); ClockworkSmsResult result = clockWorkSmsService.send(sms); if(result.isSuccess()) { System.out.println("Sent with ID: " + result.getId()); } else { System.out.println("Error: " + result.getErrorMessage()); } } catch (ClockworkException e) { e.printStackTrace(); } } } 
+5
source share
2 answers

If it is a secure REST API. Look here

If this is just the HTTP resource you need access to, see Apache HTTPClient and tutorials .

There are hundreds of resources, please try to then ask specific questions.

+2
source

In fact, we need to override the existing default behavior and add allow all as trusted servers. Below code snippet will help you:

  /* START of the fix*/ TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); /* End of the fix*/ 
0
source

Source: https://habr.com/ru/post/1232972/


All Articles