2016-01-20 105 views
1

我要送GET请求一些API不带任何参数,所以我写的代码:Java-Spring:如何向http url发送http请求?

public Boolean getData(String apiUrl) { 

     try { 
      RestTemplate restTemplate = new RestTemplate(); 
      ResponseEntity<String> responseEntity = restTemplate.getForEntity(apiUrl, String.class); 

      if (responseEntity.getStatusCode().toString().equals("200")) { 
       theLogger.info("Server successfully answered with response code: {} - {}", responseEntity.getStatusCode().toString(), responseEntity.getBody()); 
       return true; 
      } else { 
       theLogger.error("Something goes wrong! Server answered with response code: {} and error: {}", responseEntity.getStatusCode().toString(), responseEntity.getBody()); 
       return false; 
      } 

     } catch (Exception theException) { 
      theException.printStackTrace(); 
      theLogger.error("Cannot send channelInfo! Exception: " + theException); 
      return false; 
     } 

} 

它的工作原理,当API URL是http,但不使用HTTPS工作。它说:

sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target; nested exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target 

我相信这是因为我的代码不信任此证书。但我不知道该怎么办? API是公开的,它在任何网页浏览器中打开,它只是一些https网站。我无法相信我应该为所有与我一起工作的https站点下载证书,并在某处添加此证书...我相信它应该是更常见的方式来信任这些公共站点。请有人给我一个援助之手吗?

回答

0

我找到了答案here 因此,如果不得不处理由不可信任的CA颁发的证书,但在您的情况下,您并不真正关心信任。制作HTTPS呼叫之前

import javax.net.ssl.*; 
import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 

public class SSLCertificateValidation { 

    public static void disable() { 
     try { 
      SSLContext sslc = SSLContext.getInstance("TLS"); 
      TrustManager[] trustManagerArray = { new NullX509TrustManager() }; 
      sslc.init(null, trustManagerArray, null); 
      HttpsURLConnection.setDefaultSSLSocketFactory(sslc.getSocketFactory()); 
      HttpsURLConnection.setDefaultHostnameVerifier(new NullHostnameVerifier()); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private static class NullX509TrustManager implements X509TrustManager { 
     public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      System.out.println(); 
     } 
     public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { 
      System.out.println(); 
     } 
     public X509Certificate[] getAcceptedIssuers() { 
      return new X509Certificate[0]; 
     } 
    } 

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

} 

调用SSLCertificateValidation.disable():您可以通过代码禁用SSL证书验证。