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

被折叠的 条评论
为什么被折叠?



