使用Maven和Java 11的带有SSL的HTTP GET请求

vbkedwbf  于 2022-10-05  发布在  Maven
关注(0)|答案(1)|浏览(193)

我正在尝试用SSL发出一个HTTP GET请求,以检查到远程服务器的连接是否正常工作,我在互联网上找到了几个例子,但没有一个是完全解析的,似乎Java正在不断地改变,反对和删除旧的类和方法。

以下是我所能获得的最大解析代码(有些行仍然无法解析):

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.net.ssl.SSLContext;
import org.apache.http.ssl.SSLContexts;
//import org.apache.http.conn.ssl.SSLContexts;  

public class SSLContextLoader {

   public static SSLContext initSSLContext () {
      String clientKeyStorePath = ConfigManager.GetInstance().GetKeyStorePath();
      String trustStorePath = ConfigManager.GetInstance().GetTrustStorePath();
      String clientKeyStorePassword = ConfigManager.GetInstance().GetKeyStorePassword();
      String trustStorePassword = ConfigManager.GetInstance().GetTrustStorePassword();
      String keyPassword = clientKeyStorePassword;
      try {
         final KeyStore clientKeystore = KeyStore.getInstance("JKS");
         clientKeystore.load(new FileInputStream(clientKeyStorePath), clientKeyStorePassword.toCharArray());
         final KeyStore trustStore = KeyStore.getInstance("JKS");
         trustStore.load(new FileInputStream(trustStorePath), trustStorePassword.toCharArray());

         final SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(trustStore, null)
            .loadKeyMaterial(clientKeystore, keyPassword.toCharArray())
            .build();

         return sslContext;
      } catch (KeyStoreException e) {
         e.printStackTrace();
      } catch (CertificateException e) {
         e.printStackTrace();
      } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } catch (UnrecoverableKeyException e) {
         e.printStackTrace();
      } catch (KeyManagementException e) {
         e.printStackTrace();
      }
     return null;
   }
}

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;

public class GetRequest {

   private final static String ENDPOINT_URL = "https://www.google.com/";

   public void sendSSLRequest() {

      final SSLContext sslContext = SSLContextLoader.initSSLContext();

      final HttpClientBuilder clientbuilder = HttpClients.custom().setSslcontext(sslContext);
      final HttpClient client = clientbuilder.build();

      //final HttpGet request = new HttpGet(ENDPOINT_URL);
      // HttpClient httpClient = HttpClient.newHttpClient();

      HttpRequest request = HttpRequest.newBuilder()
          .uri(URI.create("https://www.google.com/"))
          .build();

      //HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); // cannot find symbols httpClient and BodyHandlers

      try {
         // the following code needs a cast to (HttpUriRequest) to parse : 
         client.execute(request);   // expecting (HttpUriRequest) and we have HttpRequest  
      } catch (final IOException e) {
         //do some exception handling...
      }
   }

}

由于找不到HTTPClient,因此未分析HTTPClient.end。

另外,由于构建器返回HttpRequest值,而Execute方法需要HttpUriRequest子类,因此没有对其进行分析。

Send和Execute是发送请求的两个备选方案(可能在不同版本的库中工作),并且都不进行解析。

下面是我对Apache库的两个maven依赖项:

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.3.5</version>
         <type>jar</type>
     </dependency>
   <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpcore</artifactId>
        <version>4.4.8</version>
    </dependency>
ogsagwnx

ogsagwnx1#

您需要以不同的方式生成HttpUriRequest作为其接口,因此您必须使用其实现类来创建其对象并将其传递给Execute方法。还有The method setSslcontext(SSLContext) from the type HttpClientBuilder is deprecated,因此您应该使用SSLConnectionSocketFactory。

无代理

public void sendSSLRequest() {
    final SSLContext sslContext = SSLContextLoader.initSSLContext();
    final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    final CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpUriRequest request = new HttpGet(URI.create("https://www.google.com/"));
    try {
        client.execute(request);
    } catch (final IOException e) {
        // do some exception handling...
    }
}

使用代理而不使用身份验证

public void sendSSLRequest() {
    HttpHost proxy = new HttpHost("ip address", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

    final SSLContext sslContext = SSLContextLoader.initSSLContext();
    final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    final CloseableHttpClient client =
            HttpClients.custom().setSSLSocketFactory(csf).setRoutePlanner(routePlanner).build();
    HttpUriRequest request = new HttpGet(URI.create("https://www.google.com/"));
    try {
        client.execute(request);
    } catch (final IOException e) {
        // do some exception handling...
    }
}

使用带身份验证的代理

public void sendSSLRequest() {
    HttpHost proxy = new HttpHost("ip address", 8080);
    DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);

    // Client credentials
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(new AuthScope(proxy),
            new UsernamePasswordCredentials("username_admin", "secret_password"));

    // Create AuthCache instance
    AuthCache authCache = new BasicAuthCache();

    BasicScheme basicAuth = new BasicScheme();
    authCache.put(proxy, basicAuth);
    HttpClientContext context = HttpClientContext.create();
    context.setCredentialsProvider(credentialsProvider);
    context.setAuthCache(authCache);

    final SSLContext sslContext = SSLContextLoader.initSSLContext();
    final SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    final CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(csf).setRoutePlanner(routePlanner)
            .setDefaultCredentialsProvider(credentialsProvider).build();
    HttpUriRequest request = new HttpGet(URI.create("https://www.google.com/"));
    try {
        client.execute(request, context);
    } catch (final IOException e) {
        // do some exception handling...
    }
}

相关问题