如何使用Jersey Client API将GET请求发送到运行HTTPS协议的服务器.我可以使用任何示例代码吗?
如此构建您的客户
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);
从此博客文章中删除了更多详细信息:http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with
有关设置证书的信息,请参阅这个很好的回答SO问题:在Java中使用HTTPS和REST
如果您使用的是Java 6,7和8,则使用Jersey客户端的HTTPS有两个不同的版本
SSLContext sc = SSLContext.getInstance("SSL");
如果使用java 8那么
SSLContext sc = SSLContext.getInstance("TLSv1"); System.setProperty("https.protocols", "TLSv1");
请找到工作代码
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 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(); } } }
助手课程
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; } }
助手班
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]; } }
一旦开始运行应用程序将获得证书错误,从浏览器下载证书并添加到
C:\java-8\jdk1_8_0\jre\lib\security
加入cacerts,您将在以下链接中获得详细信息.
理解错误的几个有用的链接
http://www.9threes.com/2015/01/restful-java-client-with-jersey-client.html
Java:sun.security.provider.certpath.SunCertPathBuilderException:无法找到请求目标的有效证书路径
http://magicmonster.com/kb/prg/java/ssl/pkix_path_building_failed.html
导入证书后出现Java Keytool错误,"keytool错误:java.io.FileNotFoundException&Access Denied"
我已经使用SSL和基本身份验证测试了以下代码的get和post方法,你可以跳过SSL证书,你可以直接复制三个类并将jar添加到java项目中并运行.
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("-------------------------------------------------------"); } }
罐子
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"
对于Jersey 2,您需要修改代码:
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
在这里唤醒一个死的问题,但提供的答案不适用于jdk 7(我在某处读到了Oracle工程师的错误,但尚未修复).除了@Ryan提供的链接外,您还必须添加:
System.setProperty("jsse.enableSNIExtension","false");
(由许多stackoverflow答案结合在一起来解决这个问题)
完整的代码如下所示对我有用(没有设置系统属性,Client Config对我不起作用):
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());
}