Java中请求HTTPS加密的源代码

本文提供了一个Java语言实现的HTTPS访问示例代码,通过自定义信任管理器和主机名验证器来绕过证书验证,适用于测试环境。此代码示例展示了如何配置SSL上下文、设置默认的Socket工厂和主机名验证器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

HTTPS访问方法的代码,抄一个能用的DEMO吧,我测试过的,可以用、,希望对大家也有用

importjava.io.*;
importjava.net.*;
importjava.security.*;
importjava.security.cert.*;
importjava.util.*;
importjavax.net.ssl.*;

publicclassHttpsTest...{
//Wewouldneverhardcodethisliteralinarealsystem,
//thisisonlyforthisarticle.
privateStringurl="https://www.paypal.com/cn";

//Createananonymousclasstotrustallcertificates.
//Thisisbadstyle,youshouldcreateaseparateclass.
privateX509TrustManagerxtm=newX509TrustManager()...{
publicvoidcheckClientTrusted(X509Certificate[]chain,StringauthType)...{}

publicvoidcheckServerTrusted(X509Certificate[]chain,StringauthType)...{
System.out.println(
"cert:"+chain[0].toString()+",authType:"+authType);
}


publicX509Certificate[]getAcceptedIssuers()...{
returnnull;
}

}
;

//Createanclasstotrustallhosts
privateHostnameVerifierhnv=newHostnameVerifier()...{
publicbooleanverify(Stringhostname,SSLSessionsession)...{
System.out.println(
"hostname:"+hostname);
returntrue;
}

}
;

//Inthisfunctionweconfigureoursystemwithalessstringent
//hostnameverifierandX509trustmanager.Thiscodeis
//executedonce,andcallsthestaticmethodsofHttpsURLConnection
publicHttpsTest()...{
//InitializetheTLSSSLContextwith
//ourTrustManager
SSLContextsslContext=null;

try...{
sslContext
=SSLContext.getInstance("TLS");
X509TrustManager[]xtmArray
=newX509TrustManager[]...{xtm};
sslContext.init(
null,xtmArray,newjava.security.SecureRandom());
}
catch(GeneralSecurityExceptiongse)...{
//Printoutsomeerrormessageanddealwiththisexception
}


//SetthedefaultSocketFactoryandHostnameVerifier
//forjavax.net.ssl.HttpsURLConnection
if(sslContext!=null)...{
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
}


HttpsURLConnection.setDefaultHostnameVerifier(hnv);
}


//Thisfunctioniscalledperiodically,theimportantthing
//tonotehereisthatthereisnospecialcodethatneedsto
//beaddedtodealwitha"HTTPS"URL.Allofthetrust
//management,verification,ishandledbytheHttpsURLConnection.
publicvoidrun()...{
try...{
URLConnectionurlCon
=(newURL(url)).openConnection();
BufferedReaderin
=newBufferedReader(newInputStreamReader(urlCon.getInputStream()));
Stringline;

while((line=in.readLine())!=null)...{
System.out.println(line);
}


//Whateverwewanttodowiththesequotes
}
catch(MalformedURLExceptionmue)...{
mue.printStackTrace();
}
catch(IOExceptionioe)...{
ioe.printStackTrace();
}
catch(Exceptione)...{
e.printStackTrace();
}

}


publicstaticvoidmain(String[]args)...{
HttpsTesthttpsTest
=newHttpsTest();
httpsTest.run();
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值