使用HTTP(和证书)使用Java / Spring休息服务

时间:2017-07-22 03:36:44

标签: java rest apache-httpclient-4.x spring-rest

我必须使用在HTTP上运行的休息服务。制作人给了我证书和方法论据。您能告诉我如何使用该服务以及如何在代码中使用该证书。我使用的是Spring 4,Java 8.请分享代码片段。

2 个答案:

答案 0 :(得分:0)

您可以参考下面的链接,了解使用RestTemplate

访问HTTPs的RESTful服务

http://www.radcortez.com/ssl-tls-rest-server-client-with-spring-and-tomee/

Access Https Rest Service using Spring RestTemplate

答案 1 :(得分:0)

如果它只是消费者验证服务身份的单向SSL,您只需将服务提供的证书(生产者证书)导入您的信任存储(CACerts文件)或编写您自己的信任管理器。

对于2路SSL,其中服务还验证客户端的身份,您不仅需要验证服务的身份,还需要将证书发送到服务,以便服务可以对其进行决策。

以下代码段用于双向SSL,但您可以通过将发送客户端证书的部分注释到服务器,轻松地将其用于1路SSL。

    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager(){
        public X509Certificate[] getAcceptedIssuers(){return null;}
        public void checkClientTrusted(X509Certificate[] certs, String authType){}
        public void checkServerTrusted(X509Certificate[] certs, String authType){}
    }};

    // Install the all-trusting trust manager
    RestTemplate restTemplate = new RestTemplate();

    try {

        String keyPassphrase = "changeit";

        KeyStore keyStore = KeyStore.getInstance("jks");
        keyStore.load(new FileInputStream("c:\\jks\\client.jks"), keyPassphrase.toCharArray());

        KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());           
        kmfactory.init(keyStore, keyPassphrase.toCharArray());

        KeyManager[] keyManager = kmfactory.getKeyManagers();

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

        sc.init(keyManager, trustAllCerts, new SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier(new javax.net.ssl.HostnameVerifier(){

            public boolean verify(String hostname,
                    javax.net.ssl.SSLSession sslSession) {
                if (hostname.equals("localhost")) {
                    return true;
                }
                return false;
            }
        });

    } catch (Exception e) {
        ;
    }       




    System.out.println("Testing listAllUsers API-----------");


    restTemplate.setErrorHandler(new ResponseErrorHandler(){

        @Override
        public void handleError(ClientHttpResponse rs) throws IOException {
            InputStream in = rs.getBody();
            String str = new String("");
            int len =0;
            while((len = in.available()) > 0){
                byte[] bytes = new byte[len];
                in.read(bytes);
               str = str + new String (bytes, "UTF-8");

            }

            System.out.println(str);

        }

        @Override
        public boolean hasError(ClientHttpResponse rs) throws IOException {

            return false;
        }

    });
    try{

    String usersMap = restTemplate.getForObject(REST_SERVICE_URI+"/user/shailendra/", String.class);`