use of javax.net.ssl.HttpsURLConnection in project wso2-synapse by wso2.
the class SynapseConfigUtils method getURLConnection.
/**
* Returns a URLCOnnection for given URL. If the URL is https one , then URLConnectin is a
* HttpsURLCOnnection and it is configured with KeyStores given in the synapse.properties file
*
* @param url URL
* @return URLConnection for given URL
*/
public static URLConnection getURLConnection(URL url) {
try {
if (url == null) {
if (log.isDebugEnabled()) {
log.debug("Provided URL is null");
}
return null;
}
URLConnection connection;
if (url.getProtocol().equalsIgnoreCase("http") || url.getProtocol().equalsIgnoreCase("https")) {
Properties synapseProperties = SynapsePropertiesLoader.loadSynapseProperties();
String proxyHost = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_HOST);
String proxyPort = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PORT);
// get the list of excluded hosts for proxy
List<String> excludedHosts = getExcludedHostsForProxy(synapseProperties);
if (proxyHost != null && proxyPort != null && !excludedHosts.contains(proxyHost)) {
SocketAddress sockaddr = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort));
Proxy proxy = new Proxy(Proxy.Type.HTTP, sockaddr);
if (url.getProtocol().equalsIgnoreCase("https")) {
connection = getHttpsURLConnection(url, synapseProperties, proxy);
} else {
connection = url.openConnection(proxy);
}
} else {
if (url.getProtocol().equalsIgnoreCase("https")) {
connection = getHttpsURLConnection(url, synapseProperties, null);
} else {
connection = url.openConnection();
}
}
// try to see weather authentication is required
String userName = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_USER);
String password = synapseProperties.getProperty(SynapseConstants.SYNPASE_HTTP_PROXY_PASSWORD);
if (userName != null && password != null) {
String header = userName + ":" + password;
byte[] encodedHeaderBytes = new Base64().encode(header.getBytes());
String encodedHeader = new String(encodedHeaderBytes);
connection.setRequestProperty("Proxy-Authorization", "Basic " + encodedHeader);
}
} else {
connection = url.openConnection();
}
connection.setReadTimeout(getReadTimeout());
connection.setConnectTimeout(getConnectTimeout());
// if http is being used
connection.setRequestProperty("Connection", "close");
return connection;
} catch (IOException e) {
handleException("Error reading at URI ' " + url + " ' ", e);
}
return null;
}
use of javax.net.ssl.HttpsURLConnection in project wso2-synapse by wso2.
the class SynapseConfigUtils method getHttpsURLConnection.
/**
* Helper method to create a HttpSURLConnection with provided KeyStores
*
* @param url Https URL
* @param synapseProperties properties for extracting info
* @param proxy if there is a proxy
* @return gives out the connection created
*/
private static HttpsURLConnection getHttpsURLConnection(URL url, Properties synapseProperties, Proxy proxy) {
if (log.isDebugEnabled()) {
log.debug("Creating a HttpsURL Connection from given URL : " + url);
}
KeyManager[] keyManagers = null;
TrustManager[] trustManagers = null;
IdentityKeyStoreInformation identityInformation = KeyStoreInformationFactory.createIdentityKeyStoreInformation(synapseProperties);
if (identityInformation != null) {
KeyManagerFactory keyManagerFactory = identityInformation.getIdentityKeyManagerFactoryInstance();
if (keyManagerFactory != null) {
keyManagers = keyManagerFactory.getKeyManagers();
}
} else {
if (log.isDebugEnabled()) {
log.debug("There is no private key entry store configuration." + " Will use JDK's default one");
}
}
TrustKeyStoreInformation trustInformation = KeyStoreInformationFactory.createTrustKeyStoreInformation(synapseProperties);
if (trustInformation != null) {
TrustManagerFactory trustManagerFactory = trustInformation.getTrustManagerFactoryInstance();
if (trustManagerFactory != null) {
trustManagers = trustManagerFactory.getTrustManagers();
}
} else {
if (log.isDebugEnabled()) {
log.debug("There is no trusted certificate store configuration." + " Will use JDK's default one");
}
}
try {
HttpsURLConnection connection;
if (proxy != null) {
connection = (HttpsURLConnection) url.openConnection(proxy);
} else {
connection = (HttpsURLConnection) url.openConnection();
}
// Create a SSLContext
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(keyManagers, trustManagers, null);
connection.setSSLSocketFactory(sslContext.getSocketFactory());
if (trustInformation != null) {
// Determine is it need to overwrite default Host Name verifier
boolean enableHostnameVerifier = true;
String value = trustInformation.getParameter(KeyStoreInformation.ENABLE_HOST_NAME_VERIFIER);
if (value != null) {
enableHostnameVerifier = Boolean.parseBoolean(value);
}
if (!enableHostnameVerifier) {
if (log.isDebugEnabled()) {
log.debug("Overriding default HostName Verifier." + "HostName verification disabled");
}
connection.setHostnameVerifier(new javax.net.ssl.HostnameVerifier() {
public boolean verify(String hostname, javax.net.ssl.SSLSession session) {
if (log.isTraceEnabled()) {
log.trace("HostName verification disabled");
log.trace("Host: " + hostname);
log.trace("Peer Host: " + session.getPeerHost());
}
return true;
}
});
} else {
if (log.isDebugEnabled()) {
log.debug("Using default HostName verifier...");
}
}
}
return connection;
} catch (NoSuchAlgorithmException e) {
handleException("Error loading SSLContext ", e);
} catch (KeyManagementException e) {
handleException("Error initiation SSLContext with KeyManagers", e);
} catch (IOException e) {
handleException("Error opening a https connection from URL : " + url, e);
}
return null;
}
use of javax.net.ssl.HttpsURLConnection in project portal by ixinportal.
the class WeixinUtil1 method httpRequest.
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
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);
// 设置请求方式(GET/POST)
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 = JSON.parseObject(buffer.toString());
} catch (ConnectException ce) {
log.error("Weixin server connection timed out.");
} catch (Exception e) {
log.error("https request error:{}", e);
}
return jsonObject;
}
use of javax.net.ssl.HttpsURLConnection in project -Netflix-CS122B by cxk123.
the class VerifyUtils method verify.
public static boolean verify(String gRecaptchaResponse) {
if (gRecaptchaResponse == null || gRecaptchaResponse.length() == 0) {
return false;
}
try {
URL verifyUrl = new URL(SITE_VERIFY_URL);
// Open Connection to URL
HttpsURLConnection conn = (HttpsURLConnection) verifyUrl.openConnection();
// Add Request Header
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "Mozilla/5.0");
conn.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Data will be sent to the server.
String postParams = "secret=" + MyConstants.SECRET_KEY + "&response=" + gRecaptchaResponse;
// Send Request
conn.setDoOutput(true);
// Get the output stream of Connection
// Write data in this stream, which means to send data to Server.
OutputStream outStream = conn.getOutputStream();
outStream.write(postParams.getBytes());
outStream.flush();
outStream.close();
// Response code return from server.
int responseCode = conn.getResponseCode();
System.out.println("responseCode=" + responseCode);
// Get the InputStream from Connection to read data sent from the server.
InputStream is = conn.getInputStream();
JsonReader jsonReader = Json.createReader(is);
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();
// ==> {"success": true}
System.out.println("Response: " + jsonObject);
boolean success = jsonObject.getBoolean("success");
return success;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
use of javax.net.ssl.HttpsURLConnection in project SocialHelper by arvinljw.
the class SocialUtil method get.
static String get(URL url) throws Exception {
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while (-1 != (len = is.read(buffer))) {
out.write(buffer, 0, len);
out.flush();
}
return out.toString("utf-8");
}
return null;
}
Aggregations