本文整理汇总了Java中javax.net.ssl.HttpsURLConnection.setSSLSocketFactory方法的典型用法代码示例。如果您正苦于以下问题:Java HttpsURLConnection.setSSLSocketFactory方法的具体用法?Java HttpsURLConnection.setSSLSocketFactory怎么用?Java HttpsURLConnection.setSSLSocketFactory使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类javax.net.ssl.HttpsURLConnection
的用法示例。
在下文中一共展示了HttpsURLConnection.setSSLSocketFactory方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: createRequest
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static URLConnection createRequest(String strUrl, String strMethod) throws Exception {
URL url = new URL(strUrl);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
if (conn instanceof HttpsURLConnection) {
HttpsURLConnection httpsConn = (HttpsURLConnection) conn;
httpsConn.setRequestMethod(strMethod);
httpsConn.setSSLSocketFactory(getSSLSF());
httpsConn.setHostnameVerifier(getVerifier());
} else if (conn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod(strMethod);
}
return conn;
}
示例2: createConnectionGet
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 创建连接
*
* @return
* @throws ProtocolException
*/
private HttpURLConnection createConnectionGet(String encoding) throws ProtocolException {
HttpURLConnection httpURLConnection = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
LogUtil.writeErrorLog(e.getMessage(), e);
return null;
}
httpURLConnection.setConnectTimeout(this.connectionTimeout);// 连接超时时间
httpURLConnection.setReadTimeout(this.readTimeOut);// 读取结果超时时间
httpURLConnection.setUseCaches(false);// 取消缓存
httpURLConnection.setRequestProperty("Content-type",
"application/x-www-form-urlencoded;charset=" + encoding);
httpURLConnection.setRequestMethod("GET");
if ("https".equalsIgnoreCase(url.getProtocol())) {
HttpsURLConnection husn = (HttpsURLConnection) httpURLConnection;
//是否验证https证书,测试环境请设置false,生产环境建议优先尝试true,不行再false
if(!SDKConfig.getConfig().isIfValidateRemoteCert()){
husn.setSSLSocketFactory(new BaseHttpSSLSocketFactory());
husn.setHostnameVerifier(new BaseHttpSSLSocketFactory.TrustAnyHostnameVerifier());//解决由于服务器证书问题导致HTTPS无法访问的情况
}
return husn;
}
return httpURLConnection;
}
示例3: doGet
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Get 请求
*
* @param pathUrl
* @param queryString
* @return
*/
public static String doGet(String pathUrl, String queryString) {
StringBuilder repString = new StringBuilder();
String path = pathUrl;
if (null != queryString && !"".equals(queryString)) {
path = path + "?" + queryString;
}
HttpsURLConnection.setDefaultHostnameVerifier(ignoreHostnameVerifier);
try {
HttpsURLConnection connection = (HttpsURLConnection) (new URL(path)).openConnection();
TrustManager[] tm = {ignoreCertificationTrustManger};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
connection.setSSLSocketFactory(ssf);
InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "utf-8");
BufferedReader br = new BufferedReader(isr);
String s;
while (null != (s = br.readLine())) {
repString.append(s);
}
isr.close();
connection.disconnect();
} catch (Exception ex) {
log.error("调用链接失败:pathUrl:" + pathUrl + "queryString:" + queryString);
log.error(ex.getMessage());
} finally {
log.info(repString.toString());
}
return repString.toString();
}
示例4: varyAndHttps
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Test public void varyAndHttps() throws Exception {
assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(sslClient.socketFactory, false);
server.enqueue(new MockResponse().addHeader("Cache-Control: max-age=60")
.addHeader("Vary: Accept-Language")
.setBody("A"));
server.enqueue(new MockResponse().setBody("B"));
URL url = server.url("/").url();
HttpsURLConnection connection1 = (HttpsURLConnection) urlFactory.open(url);
connection1.setSSLSocketFactory(sslClient.socketFactory);
connection1.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
connection1.addRequestProperty("Accept-Language", "en-US");
assertEquals("A", readAscii(connection1));
HttpsURLConnection connection2 = (HttpsURLConnection) urlFactory.open(url);
connection2.setSSLSocketFactory(sslClient.socketFactory);
connection2.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
connection2.addRequestProperty("Accept-Language", "en-US");
assertEquals("A", readAscii(connection2));
}
示例5: prepareConnection
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private HttpURLConnection prepareConnection(Request request) throws IOException, RequestFailedException {
final URL url = new URL(endpoint, MethodNameConverter.convert(request));
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (this.ignoreSllExceptions && connection instanceof HttpsURLConnection) {
HttpsURLConnection sslConnection = (HttpsURLConnection) connection;
try {
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{new TrustEverythingManager()}, new SecureRandom());
sslConnection.setHostnameVerifier(new DisabledHostnameVerifier());
sslConnection.setSSLSocketFactory(sslContext.getSocketFactory());
} catch (Exception e) {
throw new RequestFailedException(e);
}
}
connection.setRequestMethod("POST");
if (this.username != null && this.password != null) {
String authorization = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));
connection.addRequestProperty("Authorization", "Basic " + authorization);
}
return connection;
}
示例6: testExcludedCiphers
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* Test that verifies that excluded ciphers (SSL_RSA_WITH_RC4_128_SHA,
* TLS_ECDH_ECDSA_WITH_RC4_128_SHA,TLS_ECDH_RSA_WITH_RC4_128_SHA,
* TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,TLS_ECDHE_RSA_WITH_RC4_128_SHA) are not
* available for negotiation during SSL connection.
*/
@Test
public void testExcludedCiphers() throws Exception {
URL url = new URL(baseUrl, "/echo?a=b&c=d");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
= new PrefferedCipherSSLSocketFactory(sslSocketF,
excludeCiphers.split(","));
conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
assertFalse("excludedCipher list is empty", excludeCiphers.isEmpty());
try {
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copyBytes(in, out, 1024);
fail("No Ciphers in common, SSLHandshake must fail.");
} catch (SSLHandshakeException ex) {
LOG.info("No Ciphers in common, expected succesful test result.", ex);
}
}
示例7: testOneEnabledCiphers
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/** Test that verified that additionally included cipher
* TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA is only available cipher for working
* TLS connection from client to server disabled for all other common ciphers.
*/
@Test
public void testOneEnabledCiphers() throws Exception {
URL url = new URL(baseUrl, "/echo?a=b&c=d");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
SSLSocketFactory sslSocketF = clientSslFactory.createSSLSocketFactory();
PrefferedCipherSSLSocketFactory testPreferredCipherSSLSocketF
= new PrefferedCipherSSLSocketFactory(sslSocketF,
oneEnabledCiphers.split(","));
conn.setSSLSocketFactory(testPreferredCipherSSLSocketF);
assertFalse("excludedCipher list is empty", oneEnabledCiphers.isEmpty());
try {
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copyBytes(in, out, 1024);
assertEquals(out.toString(), "a:b\nc:d\n");
LOG.info("Atleast one additional enabled cipher than excluded ciphers,"
+ " expected successful test result.");
} catch (SSLHandshakeException ex) {
fail("Atleast one additional cipher available for successful handshake."
+ " Unexpected test failure: " + ex);
}
}
示例8: secureResponseCaching
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Test public void secureResponseCaching() throws IOException {
assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(sslClient.socketFactory, false);
server.enqueue(new MockResponse()
.addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setBody("ABC"));
HttpsURLConnection c1 = (HttpsURLConnection) openConnection(server.url("/").url());
c1.setSSLSocketFactory(sslClient.socketFactory);
c1.setHostnameVerifier(hostnameVerifier);
assertEquals("ABC", readAscii(c1));
// OpenJDK 6 fails on this line, complaining that the connection isn't open yet
String suite = c1.getCipherSuite();
List<Certificate> localCerts = toListOrNull(c1.getLocalCertificates());
List<Certificate> serverCerts = toListOrNull(c1.getServerCertificates());
Principal peerPrincipal = c1.getPeerPrincipal();
Principal localPrincipal = c1.getLocalPrincipal();
HttpsURLConnection c2 = (HttpsURLConnection) openConnection(server.url("/").url()); // cached!
c2.setSSLSocketFactory(sslClient.socketFactory);
c2.setHostnameVerifier(hostnameVerifier);
assertEquals("ABC", readAscii(c2));
assertEquals(suite, c2.getCipherSuite());
assertEquals(localCerts, toListOrNull(c2.getLocalCertificates()));
assertEquals(serverCerts, toListOrNull(c2.getServerCertificates()));
assertEquals(peerPrincipal, c2.getPeerPrincipal());
assertEquals(localPrincipal, c2.getLocalPrincipal());
}
示例9: get
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丟et璇锋眰
* @param url
* @return
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws IOException
* @throws KeyManagementException
*/
public static String get(String url,Boolean https) throws NoSuchAlgorithmException, NoSuchProviderException, IOException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(25000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(25000);
http.setRequestMethod("GET");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setHostnameVerifier(new Verifier());
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}
示例10: readOut
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
private static String readOut(URL url) throws Exception {
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(clientSslFactory.createSSLSocketFactory());
InputStream in = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
IOUtils.copyBytes(in, out, 1024);
return out.toString();
}
示例11: secureResponseCaching
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
@Test public void secureResponseCaching() throws IOException {
assumeFalse(getPlatform().equals("jdk9"));
server.useHttps(sslClient.socketFactory, false);
server.enqueue(new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
.addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
.setBody("ABC"));
HttpsURLConnection c1 = (HttpsURLConnection) urlFactory.open(server.url("/").url());
c1.setSSLSocketFactory(sslClient.socketFactory);
c1.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
assertEquals("ABC", readAscii(c1));
// OpenJDK 6 fails on this line, complaining that the connection isn't open yet
String suite = c1.getCipherSuite();
List<Certificate> localCerts = toListOrNull(c1.getLocalCertificates());
List<Certificate> serverCerts = toListOrNull(c1.getServerCertificates());
Principal peerPrincipal = c1.getPeerPrincipal();
Principal localPrincipal = c1.getLocalPrincipal();
HttpsURLConnection c2 = (HttpsURLConnection) urlFactory.open(server.url("/").url()); // cached!
c2.setSSLSocketFactory(sslClient.socketFactory);
c2.setHostnameVerifier(NULL_HOSTNAME_VERIFIER);
assertEquals("ABC", readAscii(c2));
assertEquals(2, cache.requestCount());
assertEquals(1, cache.networkCount());
assertEquals(1, cache.hitCount());
assertEquals(suite, c2.getCipherSuite());
assertEquals(localCerts, toListOrNull(c2.getLocalCertificates()));
assertEquals(serverCerts, toListOrNull(c2.getServerCertificates()));
assertEquals(peerPrincipal, c2.getPeerPrincipal());
assertEquals(localPrincipal, c2.getLocalPrincipal());
}
示例12: trustAllHosts
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* This function will install a trust manager that will blindly trust all SSL
* certificates. The reason this code is being added is to enable developers
* to do development using self signed SSL certificates on their web server.
*
* The standard HttpsURLConnection class will throw an exception on self
* signed certificates if this code is not run.
*/
private static SSLSocketFactory trustAllHosts(HttpsURLConnection connection) {
// Install the all-trusting trust manager
SSLSocketFactory oldFactory = connection.getSSLSocketFactory();
try {
// Install our all trusting manager
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
SSLSocketFactory newFactory = sc.getSocketFactory();
connection.setSSLSocketFactory(newFactory);
} catch (Exception e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
return oldFactory;
}
示例13: buildSSLConn
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
public HttpURLConnection buildSSLConn(String url)throws Exception {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, new TrustManager[]{new TrustAnyTrustManager()}, new java.security.SecureRandom());
URL console = new URL(url);
HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
conn.setSSLSocketFactory(sc.getSocketFactory());
conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
conn.setConnectTimeout(connectTimeOut);
conn.setReadTimeout(readTimeOut);
return conn;
}
示例14: httpsRequest
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* @param requestUrl
* @param requestMethod
* @param outputStr
* @return
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
TrustManager[] tm = {new MyX509TrustManager()};
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.parseObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
示例15: post
import javax.net.ssl.HttpsURLConnection; //导入方法依赖的package包/类
/**
* 鍙戦�丳ost璇锋眰
* @param url
* @param params
* @return
* @throws IOException
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
public static String post(String url, String params,Boolean https) throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
StringBuffer bufferRes = null;
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 浠庝笂杩癝SLContext瀵硅薄涓緱鍒癝SLSocketFactory瀵硅薄
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL urlGet = new URL(url);
HttpsURLConnection http = (HttpsURLConnection) urlGet.openConnection();
// 杩炴帴瓒呮椂
http.setConnectTimeout(50000);
// 璇诲彇瓒呮椂 --鏈嶅姟鍣ㄥ搷搴旀瘮杈冩參锛屽澶ф椂闂�
http.setReadTimeout(50000);
http.setRequestMethod("POST");
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setSSLSocketFactory(ssf);
http.setHostnameVerifier(new Verifier());
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
OutputStream out = http.getOutputStream();
out.write(params.getBytes("UTF-8"));
out.flush();
out.close();
InputStream in = http.getInputStream();
BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
String valueString = null;
bufferRes = new StringBuffer();
while ((valueString = read.readLine()) != null){
bufferRes.append(valueString);
}
in.close();
if (http != null) {
// 鍏抽棴杩炴帴
http.disconnect();
}
return bufferRes.toString();
}