用httpclient实现的忽视ssl的java代码
时间: 2024-04-03 21:35:54 浏览: 100
httpClient实例httpClient调用 http/https实例 忽略SSL验证
5星 · 资源好评率100%
好的,下面是使用 Apache HttpClient 实现忽略 SSL 验证的 Java 代码示例:
```java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
public class HttpUtils {
public static String sendGet(String url) throws Exception {
SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, (certificate, authType) -> true).build();
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
HttpGet request = new HttpGet(url);
BufferedReader in = new BufferedReader(new InputStreamReader(httpClient.execute(request).getEntity().getContent()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}
}
```
使用示例:
```java
String url = "https://api.example.com/data";
String response = HttpUtils.sendGet(url);
System.out.println(response);
```
这是一个简单的使用 Apache HttpClient 实现忽略 SSL 验证的 http 工具类。你可以根据自己的需要进行修改或扩展。
阅读全文