HTTPS using Jersey Client

后端 未结 5 1863
遇见更好的自我
遇见更好的自我 2020-11-28 21:18

How do I send GET requests using the Jersey Client API to a server which runs on the HTTPS protocol. Is there any sample code that I can use ?

5条回答
  •  佛祖请我去吃肉
    2020-11-28 22:23

    HTTPS using Jersey client has two different version if you are using java 6 ,7 and 8 then

    SSLContext sc = SSLContext.getInstance("SSL");
    

    If using java 8 then

    SSLContext sc = SSLContext.getInstance("TLSv1");
    System.setProperty("https.protocols", "TLSv1");
    

    Please find working code

    POM

    
        4.0.0
        WebserviceJersey2Spring
        WebserviceJersey2Spring
        0.0.1-SNAPSHOT
        war
        
            2.16
            UTF-8
        
        
            
                maven2-repository.java.net
                Java.net Repository for Maven
                http://download.java.net/maven/2/
            
        
    
        
    
            
                
                    org.glassfish.jersey
                    jersey-bom
                    ${jersey.version}
                    pom
                    import
                
            
        
    
        
    
            
            
                org.glassfish.jersey.containers
                jersey-container-servlet-core
    
            
            
                org.glassfish.jersey.media
                jersey-media-moxy
    
            
    
            
            
                org.springframework
                spring-core
                3.0.5.RELEASE
            
    
            
                org.springframework
                spring-context
                3.0.5.RELEASE
            
    
            
                org.springframework
                spring-web
                3.0.5.RELEASE
            
            
                org.glassfish.jersey.core
                jersey-client
                
    
    
    
            
            
                org.glassfish.jersey.ext
                jersey-spring3
                
                    
                        spring-context
                        org.springframework
                    
                    
                        spring-beans
                        org.springframework
                    
                    
                        spring-core
                        org.springframework
                    
                    
                        spring-web
                        org.springframework
                    
                    
                        jersey-server
                        org.glassfish.jersey.core
                    
                    
                        
                        jersey-container-servlet-core
                    
                        org.glassfish.jersey.containers
                    
                    
                        hk2
                        org.glassfish.hk2
                    
                
            
    
        
        
            src
            
                
                    maven-compiler-plugin
                    3.1
                    
                        1.7
                        1.7
                    
                
                
                    maven-war-plugin
                    2.3
                    
                        WebContent
                        false
                    
                
            
        
    
    

    JAVA CLASS

    package com.example.client;
    
    
    
    
    import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
    import org.springframework.http.HttpStatus;
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.client.Client;
    import javax.ws.rs.client.ClientBuilder;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.core.Response;
    
    public class JerseyClientGet {
        public static void main(String[] args) {
            String username = "username";
                String password = "p@ssword";
            String input = "{\"userId\":\"12345\",\"name \":\"Viquar\",\"surname\":\"Khan\",\"Email\":\"Vaquar.khan@gmail.com\"}";
            try {
            //SSLContext sc = SSLContext.getInstance("SSL");//Java 6
            SSLContext sc = SSLContext.getInstance("TLSv1");//Java 8
            System.setProperty("https.protocols", "TLSv1");//Java 8
    
    
            TrustManager[] trustAllCerts = { new InsecureTrustManager() };
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HostnameVerifier allHostsValid = new InsecureHostnameVerifier();
    
            Client client = ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier(allHostsValid).build();
    
            HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder()
                        .credentialsForBasic(username, password).credentials(username, password).build();
    
    
                client.register(feature);
                        //PUT request, if need uncomment it 
                        //final Response response = client
                        //.target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
                        //.request().put(Entity.entity(input, MediaType.APPLICATION_JSON), Response.class);
                //GET Request
                final Response response = client
                        .target("https://localhost:7002/VaquarKhanWeb/employee/api/v1/informations")
                        .request().get();
    
    
    
    
                if (response.getStatus() != HttpStatus.OK.value()) { throw new RuntimeException("Failed : HTTP error code : "
                        + response.getStatus()); }
                String output = response.readEntity(String.class);
                System.out.println("Output from Server .... \n");
                System.out.println(output);
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    HELPER CLASS

    package com.example.client;
    
    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLSession;
    
    public class InsecureHostnameVerifier implements HostnameVerifier {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    }
    

    Helper class

    package com.example.client;
    
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import javax.net.ssl.X509TrustManager;
    
    public class InsecureTrustManager implements X509TrustManager {
        /**
         * {@inheritDoc}
         */
        @Override
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            // Everyone is trusted!
        }
    
        /**
         * {@inheritDoc}
         */
        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
            // Everyone is trusted!
        }
    
        /**
         * {@inheritDoc}
         */
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }
    }
    

    Once you start running application will get Certificate error ,download certificate from browser and add into

    C:\java-8\jdk1_8_0\jre\lib\security
    

    Add into cacerts , you will get details in following links.

    Few useful link to understand error

    • http://www.9threes.com/2015/01/restful-java-client-with-jersey-client.html

      Java: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target

      http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html

      Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

    I have tested following code for get and post method with SSL and basic Authentication here you can skip SSL Certificate , you can directly copy three class and add jar into java project and run.

    package com.rest.client;
    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.EarUnearmarkCollateralInput;
    
    public class RestClientTest {
        /**
         * @param args
         */
        public static void main(String[] args) {
            try {
                //
                sslRestClientGETReport();
                //
                sslRestClientPostEarmark();
                //
                sslRestClientGETRankColl();
                //
            } 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    = "username";
        private static String       passWord    = "password";
    
        //
        public static void sslRestClientGETReport() 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://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/report";
            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 {
            //Query param Search={JSON}
            //
            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://localhost:7002/VaquarKhanWeb";
    
            //
            c.register(HttpAuthenticationFeature.basic(userName, passWord));
            target = c.target(baseUrl);
            target = target.path("employee/api/v1/informations/employee/data").queryParam("search","%7B\"name\":\"vaquar\",\"surname\":\"khan\",\"age\":\"30\",\"type\":\"admin\""%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("vaquar", "khan", "30", "E");
            //
            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://localhost:7002/VaquarKhanWeb/employee/api/v1/informations/employee";
            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("-------------------------------------------------------");
    
        }
    
    
    }
    

    Jars

    repository/javax/ws/rs/javax.ws.rs-api/2.0/javax.ws.rs-api-2.0.jar"
        repository/org/glassfish/jersey/core/jersey-client/2.6/jersey-client-2.6.jar"
        repository/org/glassfish/jersey/core/jersey-common/2.6/jersey-common-2.6.jar"
        repository/org/glassfish/hk2/hk2-api/2.2.0/hk2-api-2.2.0.jar"
        repository/org/glassfish/jersey/bundles/repackaged/jersey-guava/2.6/jersey-guava-2.6.jar"
        repository/org/glassfish/hk2/hk2-locator/2.2.0/hk2-locator-2.2.0.jar"
        repository/org/glassfish/hk2/hk2-utils/2.2.0/hk2-utils-2.2.0.jar"
        repository/org/javassist/javassist/3.15.0-GA/javassist-3.15.0-GA.jar"
        repository/org/glassfish/hk2/external/javax.inject/2.2.0/javax.inject-2.2.0.jar"
        repository/javax/annotation/javax.annotation-api/1.2/javax.annotation-api-1.2.jar"
        genson-1.3.jar"
    

提交回复
热议问题