HTTPS utilizando Jersey Client

¿Cómo envío solicitudes GET utilizando la API de Jersey Client a un servidor que se ejecuta en el protocolo HTTPS? ¿Hay algún código de muestra que pueda usar?

Construye tu cliente como tal

HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); ClientConfig config = new DefaultClientConfig(); SSLContext ctx = SSLContext.getInstance("SSL"); ctx.init(null, myTrustManager, null); config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx)); Client client = Client.create(config); 

Extraído de esta publicación de blog con más detalles: http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with

Para obtener información sobre cómo configurar sus certs, consulte esta pregunta SO tan bien contestada: Uso de HTTPS con REST en Java

HTTPS que utiliza el cliente de Jersey tiene dos versiones diferentes si usa Java 6, 7 y 8, luego

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

Si usa java 8 entonces

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

Por favor encuentre el código de trabajo

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      

CLASE JAVA

 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(); } } } 

CLASE DE AYUDANTE

 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; } } 

Clase de ayuda

 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]; } } 

Una vez que comience a ejecutar la aplicación recibirá un error de certificado, descargará el certificado del navegador y lo agregará a

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

Agregue en cacerts, obtendrá detalles en los siguientes enlaces.

Pocos enlaces útiles para comprender el error

He probado el siguiente código para obtener y publicar el método con SSL y autenticación básica. Aquí puede omitir el certificado SSL, puede copiar directamente tres clases y agregar jar al proyecto java y ejecutarlo.

 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("-------------------------------------------------------"); } } 

Paso

 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" 

Para Jersey 2 necesitarías modificar el código:

  return ClientBuilder.newBuilder() .withConfig(config) .hostnameVerifier(new TrustAllHostNameVerifier()) .sslContext(ctx) .build(); 

https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html

Aquí estoy despertando una pregunta muerta, pero las respuestas proporcionadas no funcionarán con jdk 7 (leí en algún lugar que hay un error para los ingenieros de Oracle abierto pero que aún no se ha solucionado). Junto con el enlace que proporcionó @Ryan, también deberá agregar:

System.setProperty (“jsse.enableSNIExtension”, “false”);

(Cortesía de muchas respuestas de stackoverflow combinadas para resolver esto)

El código completo se verá de la siguiente manera que funcionó para mí (sin configurar la propiedad del sistema, la configuración del cliente no funcionó para mí):

 import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.config.ClientConfig; import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.client.urlconnection.HTTPSProperties; public class ClientHelper { public static ClientConfig configureClient() { System.setProperty("jsse.enableSNIExtension", "false"); TrustManager[] certs = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; SSLContext ctx = null; try { ctx = SSLContext.getInstance("SSL"); ctx.init(null, certs, new SecureRandom()); } catch (java.security.GeneralSecurityException ex) { } HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory()); ClientConfig config = new DefaultClientConfig(); try { config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties( new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }, ctx)); } catch (Exception e) { } return config; } public static Client createClient() { return Client.create(ClientHelper.configureClient()); } 

Si está utilizando Java 8, una versión más corta para Jersey2 que la respuesta proporcionada por Aleksandr.

 SSLContext sslContext = null; try { sslContext = SSLContext.getInstance("SSL"); // Create a new X509TrustManager sslContext.init(null, getTrustManager(), null); } catch (NoSuchAlgorithmException | KeyManagementException e) { throw e; } final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true) .sslContext(sslContext).build(); return client; private TrustManager[] getTrustManager() { return new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; }