本文整理了Java中javax.net.ssl.HttpsURLConnection
类的一些代码示例,展示了HttpsURLConnection
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpsURLConnection
类的具体详情如下:
包路径:javax.net.ssl.HttpsURLConnection
类名称:HttpsURLConnection
[英]An HttpURLConnection for HTTPS (RFC 2818). A connected HttpsURLConnection allows access to the negotiated cipher suite, the server certificate chain, and the client certificate chain if any.
If an application wants to trust Certificate Authority (CA) certificates that are not part of the system, it should specify its own X509TrustManager via a SSLSocketFactory set on the HttpsURLConnection. The X509TrustManager can be created based on a KeyStore using a TrustManagerFactory to supply trusted CA certificates. Note that self-signed certificates are effectively their own CA and can be trusted by including them in a KeyStore.
For example, to trust a set of certificates specified by a KeyStore:
KeyStore keyStore = ...;
It is possible to implement X509TrustManager directly instead of using one created by a TrustManagerFactory. While this is straightforward in the insecure case of allowing all certificate chains to pass verification, writing a proper implementation will usually want to take advantage of java.security.cert.CertPathValidator. In general, it might be better to write a custom KeyStore implementation to pass to the TrustManagerFactory than to try and write a custom X509TrustManager.
A custom X509KeyManager can be used to supply a client certificate and its associated private key to authenticate a connection to the server. The X509KeyManager can be created based on a KeyStore using a KeyManagerFactory.
For example, to supply client certificates from a KeyStore:
KeyStore keyStore = ...;
A X509KeyManager can also be implemented directly. This can allow an application to return a certificate and private key from a non- KeyStore source or to specify its own logic for selecting a specific credential to use when many may be present in a single KeyStore.
This class attempts to create secure connections using common TLS extensions and SSL deflate compression. Should that fail, the connection will be retried with SSLv3 only.
[中]HTTPS(RFC 2818)的HttpURLConnection。连接的HttpsURLConnection允许访问协商的密码套件、服务器证书链和客户端证书链(如果有)。
####提供特定于应用程序的X509TrustManager
如果应用程序希望信任不属于系统的证书颁发机构(CA)证书,则应通过HttpsURLConnection上设置的SSLSocketFactory指定其自己的X509TrustManager。X509TrustManager可以使用TrustManagerFactory基于密钥库创建,以提供受信任的CA证书。请注意,自签名证书实际上是它们自己的CA,可以通过将它们包含在密钥库中来信任它们。
例如,要信任密钥库指定的一组证书:
KeyStore keyStore = ...;
可以直接实现X509TrustManager,而不是使用TrustManagerFactory创建的。虽然这在允许所有证书链通过验证的不安全情况下很简单,但编写适当的实现通常需要利用java。安全cert.CertPathValidator。通常,编写自定义密钥库实现以传递给TrustManagerFactory可能比尝试编写自定义X509TrustManager要好。
####提供特定于应用程序的X509KeyManager
自定义X509KeyManager可用于提供客户端证书及其关联私钥,以验证与服务器的连接。X509KeyManager可以使用KeyManagerFactory基于密钥库创建。
例如,要从密钥库提供客户端证书,请执行以下操作:
KeyStore keyStore = ...;
X509KeyManager也可以直接实现。这可以允许应用程序从非密钥库源返回证书和私钥,或者指定自己的逻辑,以便在单个密钥库中可能存在多个凭据时选择要使用的特定凭据。
####TLS不容忍支持
此类尝试使用公共TLS扩展和SSL deflate压缩创建安全连接。如果失败,将仅使用SSLv3重试连接。
代码示例来源:origin: jmdhappy/xxpay-master
public String httpPost(String url) {
StringBuffer sb = new StringBuffer();
try {
URL console = new URL(url);
if("https".equals(console.getProtocol())) {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
new java.security.SecureRandom());
HttpsURLConnection con = (HttpsURLConnection) console.openConnection();
con.setSSLSocketFactory(sc.getSocketFactory());
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setConnectTimeout(30 * 1000);
con.setReadTimeout(60 * 1000);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()), 1024*1024);
while (true) {
String line = in.readLine();
}else if("http".equals(console.getProtocol())) {
HttpURLConnection con = (HttpURLConnection) console.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setConnectTimeout(30 * 1000);
代码示例来源:origin: jfinal/jfinal
private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
URL _url = new URL(url);
HttpURLConnection conn = (HttpURLConnection)_url.openConnection();
if (conn instanceof HttpsURLConnection) {
((HttpsURLConnection)conn).setSSLSocketFactory(sslSocketFactory);
((HttpsURLConnection)conn).setHostnameVerifier(trustAnyHostnameVerifier);
}
conn.setRequestMethod(method);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setConnectTimeout(19000);
conn.setReadTimeout(19000);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
if (headers != null && !headers.isEmpty()) {
for (Entry<String, String> entry : headers.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
}
return conn;
}
代码示例来源:origin: stackoverflow.com
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCertificates, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(trustAllHostnames);
代码示例来源:origin: SonarSource/sonarqube
void trust(HttpURLConnection connection) {
if (connection instanceof HttpsURLConnection) {
HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
httpsConnection.setSSLSocketFactory(socketFactory);
httpsConnection.setHostnameVerifier(hostnameVerifier);
}
}
代码示例来源:origin: knowm/XChange
static ReturnCurrenciesResponse allCurrenciesStatic() throws IOException {
HttpsURLConnection c =
(HttpsURLConnection) new URL("https://api.idex.market/returnCurrencies").openConnection();
c.setRequestMethod("POST");
c.setRequestProperty("Accept-Encoding", "gzip");
c.setRequestProperty("User-Agent", "irrelevant");
try (InputStreamReader inputStreamReader =
new InputStreamReader(new GZIPInputStream(c.getInputStream()))) {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readerFor(ReturnCurrenciesResponse.class).readValue(inputStreamReader);
}
}
}
代码示例来源:origin: knowm/XChange
SSLContext sslContext = SSLContext.getInstance("TLS");
X509TrustManager[] xtmArray = new X509TrustManager[] {xtm};
sslContext.init(null, xtmArray, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hnv);
HttpsURLConnection httpsUrlConn = (HttpsURLConnection) (new URL(serverUrl)).openConnection();
httpsUrlConn.setRequestMethod("POST");
conn = httpsUrlConn;
} else {
URL url = new URL(serverUrl);
conn = url.openConnection();
conn.setConnectTimeout(connectTimeout * 1000);
conn.setReadTimeout(readTimeout * 1000);
conn.setRequestProperty("Content-Type", "application/json;charset=" + charset);
conn.setDoOutput(true);
代码示例来源:origin: Javen205/IJPay
sslContext.init(kms, null, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL _url = new URL(url);
conn = (HttpsURLConnection) _url.openConnection();
conn.setConnectTimeout(25000);
conn.setReadTimeout(25000);
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("User-Agent", DEFAULT_USER_AGENT);
conn.connect();
out = conn.getOutputStream();
out.write(data.getBytes(Charsets.UTF_8));
out.flush();
inputStream = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream, Charsets.UTF_8));
StringBuilder sb = new StringBuilder();
IOUtils.closeQuietly(inputStream);
if (conn != null) {
conn.disconnect();
代码示例来源:origin: stackoverflow.com
KeyStore clientStore = KeyStore.getInstance("PKCS12");
clientStore.load(new FileInputStream("test.p12"), "testPass".toCharArray());
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(clientStore, "testPass".toCharArray());
KeyManager[] kms = kmf.getKeyManagers();
KeyStore trustStore = KeyStore.getInstance("JKS");
trustStore.load(new FileInputStream("cacerts"), "changeit".toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(trustStore);
TrustManager[] tms = tmf.getTrustManagers();
SSLContext sslContext = null;
sslContext = SSLContext.getInstance("TLS");
sslContext.init(kms, tms, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
URL url = new URL("https://www.testurl.com");
HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
代码示例来源:origin: stackoverflow.com
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
System.out.println("getAcceptedIssuers =============");
System.out.println("checkServerTrusted =============");
} }, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(
sslContext.getSocketFactory());
.setDefaultHostnameVerifier(new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
System.out.println("hostnameVerifier =============");
URL url = new URL("https://www.verisign.net");
URLConnection conn = url.openConnection();
BufferedReader reader =
new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
代码示例来源:origin: jmdhappy/xxpay-master
public static byte[] httpsRequestByte(String requestUrl, String requestMethod, String outputStr) {
try {
TrustManager[] tm = { new JEEWeiXinX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestMethod(requestMethod);
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
代码示例来源:origin: stackoverflow.com
private void setupAndConnect() {
URL url = new URL("https://host.dom/xyz");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(/*keyManagers*/null, /*trustManagers*/null, /*new SecureRandom()*/null); // simple here
conn.setSSLSocketFactory(new SecureSSLSocketFactory(sslContext.getSocketFactory(), new MyHandshakeCompletedListener()));
// conn.set... /* set other parameters */
conn.connect();
代码示例来源:origin: stackoverflow.com
private InputStream getInputStream(String urlStr, String user, String password) throws IOException
{
URL url = new URL(urlStr);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
// Create the SSL connection
SSLContext sc;
sc = SSLContext.getInstance("TLS");
sc.init(null, null, new java.security.SecureRandom());
conn.setSSLSocketFactory(sc.getSocketFactory());
// Use this if you need SSL authentication
String userpass = user + ":" + password;
String basicAuth = "Basic " + Base64.encodeToString(userpass.getBytes(), Base64.DEFAULT);
conn.setRequestProperty("Authorization", basicAuth);
// set Timeout and method
conn.setReadTimeout(7000);
conn.setConnectTimeout(7000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
// Add any data you wish to post here
conn.connect();
return conn.getInputStream();
}
代码示例来源:origin: stackoverflow.com
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(new KeyManager[0], new TrustManager[] {new DefaultTrustManager()}, new SecureRandom());
SSLContext.setDefault(ctx);
URL url = new URL("https://mms.nw.ru");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
System.out.println(conn.getResponseCode());
conn.disconnect();
代码示例来源:origin: wuyouzhuguli/FEBS-Shiro
String urlNameString = url + "?" + param;
try {
SSLContext sc = SSLContext.getInstance(SSL);
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(urlNameString);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setRequestProperty(ACCEPT, "*/*");
conn.setRequestProperty(CONNECTION, CONNECTION_VALUE);
conn.setRequestProperty(USER_AGENT, USER_AGENT_VALUE);
conn.setRequestProperty(ACCEPT_CHARSET, UTF8);
conn.setRequestProperty(CONTENTTYPE, UTF8);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.connect();
InputStream is = conn.getInputStream();
BufferedReader indata = new BufferedReader(new InputStreamReader(is));
String ret = "";
conn.disconnect();
indata.close();
} catch (Exception e) {
代码示例来源:origin: yanzhenjie/NoHttp
@Override
public Network execute(BasicRequest request) throws Exception {
URL url = new URL(request.url());
HttpURLConnection connection;
Proxy proxy = request.getProxy();
if (proxy == null)
connection = (HttpURLConnection) url.openConnection();
else
connection = (HttpURLConnection) url.openConnection(proxy);
connection.setConnectTimeout(request.getConnectTimeout());
connection.setReadTimeout(request.getReadTimeout());
connection.setInstanceFollowRedirects(false);
((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
HostnameVerifier hostnameVerifier = request.getHostnameVerifier();
if (hostnameVerifier != null)
((HttpsURLConnection) connection).setHostnameVerifier(hostnameVerifier);
代码示例来源:origin: stackoverflow.com
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
KeyStore ks = KeyStore.getInstance("JKS");
FileInputStream fis = new FileInputStream("/.../example.jks");
ks.load(fis, null);
// or ks.load(fis, "thepassword".toCharArray());
fis.close();
tmf.init(ks);
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tmf.getTrustManagers(), null);
URL url = new URL("https://somewebsite.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(sslContext.getSocketFactory());
InputStream is = conn.getInputStream();
代码示例来源:origin: stackoverflow.com
SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://gridserver:3049/cgi-bin/ls.py");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslsocketfactory);
InputStream inputstream = conn.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
String string = null;
while ((string = bufferedreader.readLine()) != null) {
System.out.println("Received " + string);
}
代码示例来源:origin: ltsopensource/light-task-scheduler
private static HttpURLConnection getConnection(URL url, String method, String ctype, Map<String, String> headerMap) throws IOException {
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection connHttps = (HttpsURLConnection) conn;
if (ignoreSSLCheck) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[]{new TrustAllTrustManager()}, new SecureRandom());
connHttps.setSSLSocketFactory(ctx.getSocketFactory());
connHttps.setHostnameVerifier(new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
conn.setRequestMethod(method);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Accept", "application/json,text/xml,text/javascript,*/*");
conn.setRequestProperty("Content-Type", ctype);
代码示例来源:origin: stackoverflow.com
private HttpURLConnection getHttpConnection(String param)
throws IOException, NoSuchAlgorithmException,
KeyManagementException {
URL url = new URL(URL + param);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
SSLContext sc;
sc = SSLContext.getInstance(TLS);
sc.init(null, null, new java.security.SecureRandom());
httpsConn.setSSLSocketFactory(sc.getSocketFactory());
}
// set Timeout and method
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod(POST);
conn.setDoInput(true);
conn.setDoOutput(true);
return conn;
}
代码示例来源:origin: apache/nifi
private int executePOST(String message) throws Exception {
final SSLContextService sslContextService = runner.getControllerService(SSL_CONTEXT_SERVICE_IDENTIFIER, SSLContextService.class);
final boolean secure = (sslContextService != null);
String endpointUrl = buildUrl(secure);
final URL url = new URL(endpointUrl);
HttpURLConnection connection;
if (secure) {
final HttpsURLConnection sslCon = (HttpsURLConnection) url.openConnection();
final SSLContext sslContext = sslContextService.createSSLContext(SSLContextService.ClientAuth.WANT);
sslCon.setSSLSocketFactory(sslContext.getSocketFactory());
connection = sslCon;
} else {
connection = (HttpURLConnection) url.openConnection();
}
connection.setRequestMethod(HTTP_POST_METHOD);
connection.setDoOutput(true);
final DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
if (message != null) {
wr.writeBytes(message);
}
wr.flush();
wr.close();
return connection.getResponseCode();
}
内容来源于网络,如有侵权,请联系作者删除!