首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在java执行https get请求?

如何在java执行https get请求?
EN

Stack Overflow用户
提问于 2018-08-02 04:22:54
回答 2查看 0关注 0票数 0

我编写了一个java客户机,它执行HTTPGET请求,没有任何问题。

代码语言:txt
复制
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请求而不是https。我期待一个简单的修改,如HttpsGet,而不是别的。没有可用的HttpsGet类。

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

EN

回答 2

Stack Overflow用户

发布于 2018-08-02 13:08:36

解决方案:

代码语言:txt
复制
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;
}
票数 0
EN

Stack Overflow用户

发布于 2018-08-02 13:53:33

这是我在Java中的https客户机,它忽略无效的证书并使用Basic进行身份验证。

代码语言:txt
复制
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;
    }
代码语言:txt
复制
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;
    }
}
代码语言:txt
复制
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 {
    }
}

也许你可以从这开始。

当然,由于你有连接,所以可以使用

代码语言:txt
复制
InputStream content = (InputStream) connection.getInputStream();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001863

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档