java - 如何从java执行https GET请求

标签 java https get

我写了一个 Java 客户端,它执行 http GET 请求没有任何问题。
现在我想修改这个客户端以执行 https获取请求。

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 客户端,它会忽略无效的证书并使用 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();

关于java - 如何从java执行https GET请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26393031/

相关文章:

java - JPA/Hibernate 级联持久不起作用

asp.net-mvc - Https:从 http 隐藏 Controller 方法

https - SOAPUI 中的响应消息以加密方式显示

java - 使用 Apache HttpClient 通过 SSL 身份验证发送 HTTP 请求

php - 使用php在sql查询中的where条件中传递数组

http - HTTP get 请求的格式

Javascript Node 请求如何发送 GET 变量

java - 如何暂停程序的执行,直到单击 Java Swing 中的按钮

java - "|="是什么意思? (管道等号运算符)

java - 使用 deps 从旧 JAR 创建模块化 JAR