JerseyClient2.x:SSLHandshakeException:java.security.cert.CertificateException:没有名称匹配..即使客户端忽略所有证书&信任所有主人

时间:2015-10-27 12:50:31

标签: ssl-certificate jersey-client

public class Testing {
static WebTarget webTarget = null;

public static void main(String args[]) throws Exception {
    webTarget = createClient();

    WebTarget webTargetWithQueryParam = webTarget.queryParam("Version", "1").queryParam("Connection", "gOpAK52by09i305CMqJsnzzD4paQd1KG%2BVgdCBJw9h%0D%0AeuAxY2");
    Invocation.Builder invocationBuilder = webTargetWithQueryParam.request(MediaType.APPLICATION_XML);
    invocationBuilder.header("Host", "stagingtenant").header("Content-Type", MediaType.APPLICATION_FORM_URLENCODED_TYPE)
    .accept("text/xml");

    Response response = invocationBuilder.post(Entity.xml(new File("..\sample.xml")));
    if (response.getStatus() != 200) {
        throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"=="+response.getStatusInfo());
    }
    String output = response.getStatusInfo().toString();
    System.out.println(output);
}

public static Client initClient(ClientConfig config) throws NoSuchAlgorithmException, KeyManagementException {

    SSLContext ctx = SSLContext.getInstance("SSL");
      TrustManager certs = 
              new X509TrustManager(){
                  public X509Certificate[] getAcceptedIssuers(){ return new X509Certificate[0];}
                  public void checkClientTrusted(X509Certificate[] certs, String authType){}
                  public void checkServerTrusted(X509Certificate[] certs, String authType){}
              };

        ctx.init(null, new TrustManager[]{certs}, new SecureRandom());
        return ClientBuilder.newBuilder()
            .sslContext(ctx)
            .withConfig((javax.ws.rs.core.Configuration) config)
            .hostnameVerifier(new TrustAllHostNameVerifier() {

                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            })

            .build();
}

public  static class TrustAllHostNameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
    return true;
}
}

  public static WebTarget createClient() throws KeyManagementException, NoSuchAlgorithmException{
      ClientConfig clientConfig = new ClientConfig();
      Client client = initClient(clientConfig);
      client.register(new LoggingFilter());
      HttpAuthenticationFeature feature = HttpAuthenticationFeature.universalBuilder().credentialsForDigest("username", "password").build();
      client.register(feature);
      WebTarget webTarget = client.target("https://stagingtenant/apc/dig/ingestion/transcript");
      return webTarget;
  }
}

响应:

  

SEVERE:提交请求输出流时出错。   javax.net.ssl.SSLHandshakeException:   java.security.cert.CertificateException:没有名称匹配   找到了一位发现者   sun.security.ssl.Alerts.getSSLException(Alerts.java:192)

1 个答案:

答案 0 :(得分:0)

fwiw,一个使用" RestEasy"实施JAX-RS 2.x以建立一个特殊的"信任所有"客户...

    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.security.GeneralSecurityException;
    import java.security.KeyManagementException;
    import java.security.KeyStoreException;
    import java.security.NoSuchAlgorithmException;
    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    import java.util.ArrayList;
    import java.util.Arrays;
    import javax.ejb.Stateless;
    import javax.net.ssl.SSLContext;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.Produces;
    import org.apache.logging.log4j.LogManager;
    import org.apache.logging.log4j.Logger;
    import javax.ws.rs.client.Entity;
    import javax.ws.rs.core.MediaType;
    import javax.ws.rs.core.Response;
    import org.apache.http.config.Registry;
    import org.apache.http.config.RegistryBuilder;
    import org.apache.http.conn.HttpClientConnectionManager;
    import org.apache.http.conn.ssl.TrustStrategy;
    import org.jboss.resteasy.client.jaxrs.ResteasyClient;
    import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
    import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
    import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
    import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
    import org.apache.http.conn.socket.ConnectionSocketFactory;
    import org.apache.http.conn.ssl.NoopHostnameVerifier;
    import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClientBuilder;
    import org.apache.http.ssl.SSLContexts;

    @Stateless
    @Path("/postservice")
    public class PostService {

        private static final Logger LOG = LogManager.getLogger("PostService");

        public PostService() {
        }

        @GET
        @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
        public PostRespDTO get() throws NoSuchAlgorithmException, KeyManagementException, MalformedURLException, IOException, GeneralSecurityException {

            //...object passed to the POST method...
            PostDTO requestObject = new PostDTO();
            requestObject.setEntryAList(new ArrayList<>(Arrays.asList("ITEM0000A", "ITEM0000B", "ITEM0000C")));
            requestObject.setEntryBList(new ArrayList<>(Arrays.asList("AAA", "BBB", "CCC")));

            //...build special "trust all" client to call POST method...
            ApacheHttpClient4Engine engine = new ApacheHttpClient4Engine(createTrustAllClient());

            ResteasyClient client = new ResteasyClientBuilder().httpEngine(engine).build();
            ResteasyWebTarget target = client.target("https://localhost:7002/postRespWS").path("postrespservice");
            Response response = target.request().accept(MediaType.APPLICATION_JSON).post(Entity.entity(requestObject, MediaType.APPLICATION_JSON));

            //...object returned from the POST method...
            PostRespDTO responseObject = response.readEntity(PostRespDTO.class);

            response.close();

            return responseObject;
        }


        //...get special "trust all" client...
        private static CloseableHttpClient createTrustAllClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

            SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, TRUSTALLCERTS).useProtocol("TLS").build();
            HttpClientBuilder builder = HttpClientBuilder.create();
            NoopHostnameVerifier noop = new NoopHostnameVerifier();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, noop);
            builder.setSSLSocketFactory(sslConnectionSocketFactory);
            Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslConnectionSocketFactory).build();
            HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry);
            builder.setConnectionManager(ccm);

            return builder.build();
        }


        private static final TrustStrategy TRUSTALLCERTS = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType)
                throws CertificateException {
                return true;
            }
        };
    }

相关的Maven依赖

    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-client</artifactId>
        <version>3.0.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>jaxrs-api</artifactId>
        <version>3.0.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jackson2-provider</artifactId>
        <version>3.0.10.Final</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>