发送HTTPS请求,获得网页内容的java方法
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
这是一个java方法,其功能是发送https请求,获得相应的页面内容..最后返回字符串
/**
* 发送HTTPS请求,获得网页内容
* @param urlstr
* @return
* @throws IOException
*/
@Test
public String testHtml2(String urlstr) {
//System.out.println("############");
String sCurrentLine;
String sTotalString;
sCurrentLine = "";
sTotalString = "";
String hsUrl = "https://localhost:8443/BestServer/login!Checking.do?string="+urlstr;
URL url ;
try {
url = new URL(hsUrl);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
X509TrustManager xtm = new X509TrustManager() {
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1)
throws CertificateException {
// TODO Auto-generated method stub
}
};
TrustManager[] tm = { xtm };
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, tm, null);
con.setSSLSocketFactory(ctx.getSocketFactory());
con.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
InputStream l_urlStream = con.getInputStream();;
BufferedReader l_reader = new BufferedReader(new InputStreamReader(
l_urlStream));
while ((sCurrentLine = l_reader.readLine()) != null) {
sTotalString += sCurrentLine + "\r\n";
}
//System.out.println(sTotalString.trim());
} catch (Exception e) {
e.printStackTrace();
}
return sTotalString.trim();
}