import java.io.*;
import javax.net.ssl.*;
//import java.io.IOException;
//import java.io.InputStream;
//import java.io.OutputStream;
//import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.Socket;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
/**
* @author lwh
* @date 2022/1/12
*/
public class Clientsocket {
public static String sentRequest(String path, HttpMethod method, Map<String,String> properties,Map<String, String> params) {
HttpsURLConnection connection = null;
StringBuffer buffer = new StringBuffer();
try{
//信任策略,我自己实现的策略,无需验证服务器的ssl证书
TrustManager[] tm = {new NonValidationVerX509TrustManager()};
//getInstance的第一个参数,具体查看https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL");
//第一个参数:密码仓库,我不需要验证证书,所以不需要,设置为空
//第二个参数:信任策略,传我自己的
//第三个参数:随机数
sslContext.init(null, tm, new SecureRandom());
//创建socket工厂
SSLSocketFactory socketFactory = sslContext.getSocketFactory();
//创建访问的url
URL url = new URL(path);
//获取HttpsURLConnection对象
connection = (HttpsURLConnection) url.openConnection();
//设置socket工厂
connection.setSSLSocketFactory(socketFactory);
//设置请求方式
connection.setRequestMethod(method.toString());
connection.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
//设置Property
HttpsURLConnection finalConnection = connection;
if(properties!=null){
for (Map.Entry<String, String> entry : properties.entrySet()) {
connection.setRequestProperty(entry.getKey(),entry.getValue());
}
}
//设置请求参数
if(params!=null){
try(final OutputStreamWriter outputStream = new OutputStreamWriter(connection.getOutputStream());){
StringBuilder param = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
if (param.length() > 0) {
param.append("&");
}
param.append(entry.getKey());
param.append("=");
param.append(entry.getValue());
}
System.out.println("param:" + param.toString());
outputStream.write(param.toString());
}
}
//处理结果
if(connection.getResponseCode()==200){
try(InputStream inputStream = connection.getInputStream();){
final byte[] buf = new byte[1024];
int len = 0;
while ((len =inputStream.read(buf) )!=-1){
buffer.append(new String(buf,0,len, StandardCharsets.UTF_8));
}
}
}
} catch (MalformedURLException | NoSuchAlgorithmException | KeyManagementException e) {
throw new RuntimeException("HttpsURLConnection 的SSL 配置异常"+e);
} catch (IOException ioEx) {
throw new RuntimeException("请求失败,原因:"+ ioEx);
} finally {
//关闭资源
if(connection!=null){
connection.disconnect();
}
}
return buffer.toString();
}
public static void main(String[] args)throws Exception{
final String s = Clientsocket.sentRequest("https://www.youtube.com", HttpMethod.GET, null, null);
System.out.println(s);
File fl=new File("/Users/wangzhong/java/1.html");
FileOutputStream os=new FileOutputStream(fl);
os.write(s.getBytes());
}
//请求类型 post/get
public static enum HttpMethod{
GET,POST;
}
public static class NonValidationVerX509TrustManager implements X509TrustManager {
/**
* 这里是服务器验证客户端证书的,这里不需要验证
* @param chain 证书链,具体查看{@link X509TrustManager}
* @param authType 基于客户端证书的认证类型 比如RSA,具体查看{@link X509TrustManager}
* @throws CertificateException
*/
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
/**
* 这里是客户端验证服务器证书的,这里不需要验证
* @param chain 证书链,具体查看{@link X509TrustManager}
* @param authType 使用的密钥交换算法,具体查看{@link X509TrustManager}
* @throws CertificateException 证书验证失败,会抛出此异常
*/
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
System.out.println("不需要验证");
}
/**
* 获取受信任的证书列表
* @return 受信任的证书列表
*/
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
}
【无标题】留存,网上下载
最新推荐文章于 2024-06-05 21:00:00 发布