【问题标题】:How to execute a https GET request from java如何从java执行https GET请求
【发布时间】:2014-10-15 22:13:26
【问题描述】:

我编写了一个 Java 客户端,它可以毫无问题地执行 http GET 请求。 现在我想修改这个客户端以执行https GET 请求。

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

private String executeGet(final String url, String proxy, int port)
        throws IOException, RequestUnsuccesfulException, InvalidParameterException {

    CloseableHttpClient httpclient = null;
    String ret = "";
    RequestConfig config;

    try {                       
        String hostname = extractHostname(url);
        logger.info("Hostname {}", hostname);

        HttpHost target = new HttpHost(hostname, 80, null);

        HttpHost myProxy = new HttpHost(proxy, port, "http");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(
                AuthScope.ANY,
                new UsernamePasswordCredentials(USERNAME, PASSWORD));

        httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();         
        config = RequestConfig.custom().setProxy(myProxy).build();


        HttpGet request = new HttpGet(url);
        request.setConfig(config);
        CloseableHttpResponse response = httpclient.execute(target, request);

        ...

我期待一个简单的修改,比如使用 HttpsGet 而不是 HttpGet 但不,没有可用的 HttpsGet 类。

修改此方法以处理https GET 请求的最简单方法是什么?

【问题讨论】:

    标签: java https get


    【解决方案1】:

    这是我用 Java 编写的快速而肮脏的 https 客户端,它忽略无效证书并使用 BASIC 进行身份验证

    import java.io.IOException;
    import java.net.URL;
    import java.security.KeyManagementException;
    import java.security.NoSuchAlgorithmException;
    
    import javax.net.ssl.HttpsURLConnection;
    import javax.net.ssl.SSLContext;
    import javax.net.ssl.TrustManager;
    
        public static HttpsURLConnection getConnection(boolean ignoreInvalidCertificate, String user, String pass, HttpRequestMethod httpRequestMethod, URL url) throws KeyManagementException, NoSuchAlgorithmException, IOException{
            SSLContext ctx = SSLContext.getInstance("TLS");
            if (ignoreInvalidCertificate){
                ctx.init(null, new TrustManager[] { new InvalidCertificateTrustManager() }, null);  
            }       
            SSLContext.setDefault(ctx);
    
            String authStr = user+":"+pass;
            String authEncoded = Base64.encodeBytes(authStr.getBytes());
    
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    
            connection.setRequestMethod("GET");
            connection.setDoOutput(true);
            connection.setRequestProperty("Authorization", "Basic " + authEncoded);     
    
            if (ignoreInvalidCertificate){
                connection.setHostnameVerifier(new InvalidCertificateHostVerifier());
            }
    
            return connection;
        }
    

    --

    import javax.net.ssl.HostnameVerifier;
    import javax.net.ssl.SSLSession;
    
    public class InvalidCertificateHostVerifier implements HostnameVerifier{
        @Override
        public boolean verify(String paramString, SSLSession paramSSLSession) {
            return true;
        }
    }
    

    --

    import java.security.cert.CertificateException;
    import java.security.cert.X509Certificate;
    
    import javax.net.ssl.X509TrustManager;
    
    /**
     * ignore invalid Https certificate from OPAM
     * <p>see http://javaskeleton.blogspot.com.br/2011/01/avoiding-sunsecurityvalidatorvalidatore.html
     */
    public class InvalidCertificateTrustManager implements X509TrustManager{
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    
        @Override
        public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
    
        }
    
        @Override
        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString) throws CertificateException {
        }
    }
    

    也许这是你可以开始的东西。

    当然,既然你有连接,你可以使用检索响应内容

    InputStream content = (InputStream) connection.getInputStream();
    

    【讨论】:

      【解决方案2】:

      我开发了一个看起来比这里发布的更简单的解决方案

      private String executeGet(final String https_url, final String proxyName, final int port) {
          String ret = "";
      
          URL url;
          try {
      
              HttpsURLConnection con;
              url = new URL(https_url);
      
              if (proxyName.isEmpty()) {  
                  con = (HttpsURLConnection) url.openConnection();
              } else {                
                  Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyName, port));
                  con = (HttpsURLConnection) url.openConnection(proxy);
                  Authenticator authenticator = new Authenticator() {
                      public PasswordAuthentication getPasswordAuthentication() {
                              return (new PasswordAuthentication(USERNAME, PASSWORD.toCharArray()));
                          }
                      };
                  Authenticator.setDefault(authenticator);
              }
      
              ret = getContent(con);
      
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
      
          return ret;
      }
      

      【讨论】:

      • 您能否澄清 getContent 方法属于哪个类,因为我遇到了错误。
      • URL.getContent() 是 openConnection().getContent() 的快捷方式,所以我们需要查看 URLConnection.getContent() 的文档
      • 粘贴完整工作的 sn-p 是明智之举,而不是一些没有导入的代码。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-29
      • 2017-04-14
      • 1970-01-01
      • 2017-07-16
      • 2014-10-10
      • 1970-01-01
      • 2018-03-25
      相关资源
      最近更新 更多