2016-01-20 67 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證書驗證。