0

I'm doing a rest in java client where the server is an app that gives me a URL + key. example: https://api.ost.pt/agencies/?key=vkey This was enough to return the response in json. Had a client made in php and everything was fine, except that I'm moving to java and I'm with some java with difficulty because of SSL. Someone already has clients in Java with SSL? I do not understand what kind of authentication you have to do ...

Tnha the following code:

String httpsURL = "https://api.ost.pt/agencies/?key=vkey";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
  System.out.println(inputLine);
}

in.close();

The result:

Exception in thread "main" javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I did something simple but I thought it worked because in php was no longer any autenticção. They can lend a hand I have to do in Java to implement a REST client in Java?

Thanks for listening

2 Answers 2

1

It is because java does not support the cipher suites of the server. You can verify what are the cipher suites available at the server from https://www.ssllabs.com. following is a sample output.

enter image description here

In above image you can see what are the cipher suites available at server. Following code shows what are the cipher suites available with your JVM.

SSLServerSocketFactory factory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
String cSuites[] = factory.getSupportedCipherSuites();
for(String s : cSuites){
     System.out.println(s);
}

What you can do to solve your problem is download and install Java Cryptography Extension. For jdk 1.8, JCE can be downloaded here. To install JCE, simply put local_policy.jar and US_export_policy.jar inside $YOUR_JDK_HOME/jre/lib/security and $YOUR_JAVA_HOME/jre8/lib/security directories.

Now in your program, before making the connection, you can set https.cipherSuites property for one or more available cipher suites at the server. you can use https.cipherSuites property to specify which cipher suites are enabled to use with your HttpsURLConnection. However setting this property is not mandatory.

System.setProperty("https.cipherSuites", "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384,TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA");

String httpsURL = "https://api.ost.pt/agencies/?key=vkey";
URL myurl = new URL(httpsURL);
HttpsURLConnection con = (HttpsURLConnection)myurl.openConnection();
InputStream ins = con.getInputStream();
InputStreamReader isr = new InputStreamReader(ins);
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
{
     System.out.println(inputLine);
}

in.close();

NOTE: except for those cipher suites which begins with TLS_DHE_XXX.They do not work due to this known bug.

After that you can establish the connection to the server. However it still returns error code 401 due to failed authentication. For that you need to provide proper authentication details.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the clarification :) Only with the key in the URL already can get the data, but that authentication data they can ask me? Thanks :)
0

Use following code :

package com.rest.client;
    //http://apiwave.com/java/snippets/removal/org.glassfish.jersey.client.authentication.HttpAuthenticationFeature
    import java.io.IOException;
    import java.net.*;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.client.WebTarget;
    import javax.ws.rs.core.Response;
    import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
    import org.glassfish.jersey.filter.LoggingFilter;
    import com.rest.dto.Employee;

    public class RestClientTest {
        /**
         * @param args
         */
        public static void main(String[] args) {
            try {
                //
                sslRestClientGETReport();
                //
                sslRestClientPost();
                //
                sslRestClientGET();
                //
            } catch (KeyManagementException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (NoSuchAlgorithmException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        }

        //
        private static WebTarget    target      = null;
        //
        private static String       userName    = "Vkhan";
        private static String       passWord    = "Vkhan";

        //
        public static void sslRestClientGETReport() throws KeyManagementException, IOException, NoSuchAlgorithmException {
            //
            //AuthService 

            //
            SSLContext sc = SSLContext.getInstance("TLSv1");
            TrustManager[] trustAllCerts = { new InsecureTrustManager() };
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
            //
            Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
            //


            String baseUrl ="https://vaquarkhan.net/companyabc/efgd//criteria";

            c.register(HttpAuthenticationFeature.basic(userName, passWord));
            target = c.target(baseUrl);
            target.register(new LoggingFilter());
            String responseMsg = target.request().get(String.class);
            System.out.println("-------------------------------------------------------");
            System.out.println(responseMsg);
            System.out.println("-------------------------------------------------------");
            //

        }

        public static void sslRestClientGET() throws KeyManagementException, IOException, NoSuchAlgorithmException {
            //
            //
            SSLContext sc = SSLContext.getInstance("SSL");
            TrustManager[] trustAllCerts = { new InsecureTrustManager() };
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
            //
            Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
            //

            String baseUrl = "https://vaquarkhan.net/companyabc/efgd//criteria";

            //
            c.register(HttpAuthenticationFeature.basic(userName, passWord));
            target = c.target(baseUrl);
            target = target.path("vm/khan/api/v1/name").queryParam("search","%7B\"aa\":\"202\",\"bb\":\"khan\",\"tt\":\"10\",\"type\":\"OP\",\"userId\":[\"123,456\"],\"nk\":\"IM\",\"pk\":\"op\"%7D");

            target.register(new LoggingFilter());
            String responseMsg = target.request().get(String.class);
            System.out.println("-------------------------------------------------------");
            System.out.println(responseMsg);
            System.out.println("-------------------------------------------------------");
            //

        }
        //TOD need to fix
        public static void sslRestClientPost() throws KeyManagementException, IOException, NoSuchAlgorithmException {
            //
            //
            Employee employee = new Employee("123", "12345", "20", "KK",
                    null, "6786", "dfdfdf", "we", "sdsdsdsds", "4", "4");
            //
            SSLContext sc = SSLContext.getInstance("SSL");
            TrustManager[] trustAllCerts = { new InsecureTrustManager() };
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
            //
            Client c = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
            //

            String baseUrl = "https://vaquar/khan/api/v1/name";

            c.register(HttpAuthenticationFeature.basic(userName, passWord));
            target = c.target(baseUrl);
            target.register(new LoggingFilter());
            //
            Response response = target.request().put(Entity.json(employee));
            String output = response.readEntity(String.class);
            //
            System.out.println("-------------------------------------------------------");
            System.out.println(output);
            System.out.println("-------------------------------------------------------");

        }

        public static void URI( String myURL){

            try {
              URL url = new URL(myURL);
              String nullFragment = null;
              URI uri = new java.net.URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), nullFragment);
              System.out.println("URI " + uri.toString() + " is OK");
            } catch (MalformedURLException e) {
              System.out.println("URL " + myURL + " is a malformed URL");
            } catch (URISyntaxException e) {
              System.out.println("URI " + myURL + " is a malformed URL");
            }
          }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.