List of usage examples for javax.net.ssl HttpsURLConnection disconnect
public abstract void disconnect();
From source file:com.cloud.utils.UriUtils.java
public static Long getRemoteSize(String url) { Long remoteSize = (long) 0; HttpURLConnection httpConn = null; HttpsURLConnection httpsConn = null; try {//from www. j a va 2s . co m URI uri = new URI(url); if (uri.getScheme().equalsIgnoreCase("http")) { httpConn = (HttpURLConnection) uri.toURL().openConnection(); if (httpConn != null) { httpConn.setConnectTimeout(2000); httpConn.setReadTimeout(5000); String contentLength = httpConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpConn.disconnect(); } } else if (uri.getScheme().equalsIgnoreCase("https")) { httpsConn = (HttpsURLConnection) uri.toURL().openConnection(); if (httpsConn != null) { String contentLength = httpsConn.getHeaderField("content-length"); if (contentLength != null) { remoteSize = Long.parseLong(contentLength); } httpsConn.disconnect(); } } } catch (URISyntaxException e) { throw new IllegalArgumentException("Invalid URL " + url); } catch (IOException e) { throw new IllegalArgumentException("Unable to establish connection with URL " + url); } return remoteSize; }
From source file:com.daoke.mobileserver.test.TestHttps.java
public static String doPost(String url, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null;/* www. ja v a 2 s . c om*/ String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }
From source file:com.voa.weixin.utils.HttpUtils.java
/** * httpspost?/*w w w . j a va 2 s . c o m*/ * * @param url * @param param * @return * @throws Exception */ private static String doHttps(String url, String param, String method) throws Exception { HttpsURLConnection conn = null; OutputStream out = null; String rsp = null; byte[] content = param.getBytes("utf-8"); try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx); conn = getConnection(new URL(url), method, ctype); conn.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setConnectTimeout(60000); conn.setReadTimeout(60000); } catch (Exception e) { throw e; } try { out = conn.getOutputStream(); if (StringUtils.isNotBlank(param)) out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
@Test @Ignore// w w w .j a v a2 s . co m public void testCredentialManager() throws CMException, URISyntaxException, IOException { // There are 3 service username and password entries in the Keystore List<URI> serviceList = credentialManager.getServiceURIsForAllUsernameAndPasswordPairs(); assertTrue(serviceList.size() == 3); System.out.println(); assertTrue(serviceList.contains(serviceURI2)); credentialManager.deleteUsernameAndPasswordForService(serviceURI3); assertFalse(credentialManager.hasUsernamePasswordForService(serviceURI3)); // There are 2 private/public key pair entries in the Keystore credentialManager.hasKeyPair(privateKey, privateKeyCertChain); // There are Google's and heater.cs.man.ac's trusted certificates in the Truststore credentialManager.hasTrustedCertificate(trustedCertficateGoogle); // Open a HTTPS connection to Google URL url = new URL("https://code.google.com/p/taverna/"); HttpsURLConnection conn; conn = (HttpsURLConnection) url.openConnection(); // This should work conn.connect(); assertEquals("HTTP/1.1 200 OK", conn.getHeaderField(0)); conn.disconnect(); credentialManager.hasTrustedCertificate(trustedCertficateHeater); // Open a HTTPS connection to heater url = new URL("https://heater.cs.man.ac.uk:7443/"); conn = (HttpsURLConnection) url.openConnection(); // This should work conn.connect(); assertEquals("HTTP/1.1 200 OK", conn.getHeaderField(0)); conn.disconnect(); }
From source file:org.globusonline.transfer.JSONTransferAPIClient.java
public Result requestResult(String method, String path, JSONObject data, Map<String, String> queryParams) throws IOException, MalformedURLException, GeneralSecurityException, JSONException, APIError { String stringData = null;/* ww w. j av a 2 s . com*/ if (data != null) stringData = data.toString(); HttpsURLConnection c = request(method, path, stringData, queryParams); Result result = new Result(); result.statusCode = c.getResponseCode(); result.statusMessage = c.getResponseMessage(); result.document = new JSONObject(readString(c.getInputStream())); c.disconnect(); return result; }
From source file:com.camel.trainreserve.JDKHttpsClient.java
public static String doPost(String url, String cookieStr, String ctype, byte[] content, int connectTimeout, int readTimeout) throws Exception { HttpsURLConnection conn = null; OutputStream out = null;// ww w . j a v a 2 s. co m String rsp = null; try { try { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); //SSLContext.setDefault(ctx); conn = getConnection(new URL(url), METHOD_POST, ctype); conn.setSSLSocketFactory(ctx.getSocketFactory()); conn.setRequestProperty("Cookie", cookieStr); conn.setHostnameVerifier(new TrustAnyHostnameVerifier()); conn.setConnectTimeout(connectTimeout); conn.setReadTimeout(readTimeout); } catch (Exception e) { log.error("GET_CONNECTOIN_ERROR, URL = " + url, e); throw e; } try { out = conn.getOutputStream(); out.write(content); rsp = getResponseAsString(conn); } catch (IOException e) { log.error("REQUEST_RESPONSE_ERROR, URL = " + url, e); throw e; } } finally { if (out != null) { out.close(); } if (conn != null) { conn.disconnect(); } } return rsp; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call to get a new client credentials token, required for creating new account * // w w w . j a v a 2s .c o m * @param url * @param clientCredentialsToken * @param httpMethod * @param httpBody * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws ProtocolException * @throws JSONException */ public static String getClientCredentialsResponse(Context context, String url, String clientCredentialsToken, String httpMethod, Bundle httpBody) throws MalformedURLException, IOException, ProtocolException, JSONException { boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } HttpsURLConnection connection = createSecureConnection(new URL(addParameters(context, url))); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); connection.setRequestMethod(httpMethod); connection.setDoOutput(true); connection.setDoInput(true); String authValue = "Bearer " + clientCredentialsToken; connection.setRequestProperty("Authorization", authValue); connection.connect(); if (!httpBody.isEmpty()) { OutputStream os = new BufferedOutputStream(connection.getOutputStream()); os.write(encodePostBody(httpBody).getBytes()); os.flush(); } try { LoggingUtils.d(LOG_TAG, connection.toString()); response = readFromStream(connection.getInputStream()); } catch (FileNotFoundException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }
From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java
protected ConfigSchema assertReturnCode(String query, SSLContext sslContext, int expectedReturnCode) throws Exception { HttpsURLConnection httpsURLConnection = openUrlConnection(C2_URL + query, sslContext); try {// ww w. ja v a 2 s. com assertEquals(expectedReturnCode, httpsURLConnection.getResponseCode()); if (expectedReturnCode == 200) { return SchemaLoader.loadConfigSchemaFromYaml(httpsURLConnection.getInputStream()); } } finally { httpsURLConnection.disconnect(); } return null; }
From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java
public static HttpsResponse getWithBasicAuth(String Uri, String requestParameters, String userName, String password) throws IOException { if (Uri.startsWith("https://")) { String urlStr = Uri;//from w ww.j a va2s . c o m if (requestParameters != null && requestParameters.length() > 0) { urlStr += "?" + requestParameters; } URL url = new URL(urlStr); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setRequestMethod("GET"); String encode = new String( new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes())) .replaceAll("\n", ""); conn.setRequestProperty("Authorization", "Basic " + encode); conn.setDoOutput(true); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); conn.setReadTimeout(30000); conn.connect(); // Get the response StringBuilder sb = new StringBuilder(); BufferedReader rd = null; try { rd = new BufferedReader(new InputStreamReader(conn.getInputStream(), Charset.defaultCharset())); String line; while ((line = rd.readLine()) != null) { sb.append(line); } } catch (FileNotFoundException ignored) { } finally { if (rd != null) { rd.close(); } conn.disconnect(); } return new HttpsResponse(sb.toString(), conn.getResponseCode()); } return null; }
From source file:com.hybris.mobile.data.WebServiceDataProvider.java
/** * Synchronous call for logging out/* w ww.jav a 2 s .co m*/ * * @return The data from the server as a string, in almost all cases JSON * @throws MalformedURLException * @throws IOException * @throws JSONException */ public static String getLogoutResponse(Context context) throws MalformedURLException, IOException, JSONException { // Refresh if necessary if (WebServiceAuthProvider.tokenExpiredHint(context)) { WebServiceAuthProvider.refreshAccessToken(context); } boolean refreshLimitReached = false; int refreshed = 0; String response = ""; while (!refreshLimitReached) { // If we have refreshed max number of times, we will not do so again if (refreshed == 1) { refreshLimitReached = true; } URL url = new URL(urlForLogout(context)); HttpsURLConnection connection = createSecureConnection(url); trustAllHosts(); connection.setHostnameVerifier(DO_NOT_VERIFY); String authValue = "Bearer " + SDKSettings.getSharedPreferenceString(context, "access_token"); connection.setRequestMethod("POST"); connection.setRequestProperty("Authorization", authValue); connection.setDoOutput(true); connection.setDoInput(true); connection.connect(); try { LoggingUtils.d(LOG_TAG, "LogoutResponse" + connection.toString()); response = readFromStream(connection.getInputStream()); } catch (MalformedURLException e) { LoggingUtils.e(LOG_TAG, "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(), null); } catch (IOException e) { response = readFromStream(connection.getErrorStream()); } finally { connection.disconnect(); } // Allow for calls to return nothing if (response.length() == 0) { return ""; } // Check for JSON parsing errors (will throw JSONException is can't be parsed) JSONObject object = new JSONObject(response); // If no error, return response if (!object.has("error")) { return response; } // If there is a refresh token error, refresh the token else if (object.getString("error").equals("invalid_token")) { if (refreshLimitReached) { // Give up return response; } else { // Refresh the token WebServiceAuthProvider.refreshAccessToken(context); refreshed++; } } } // while(!refreshLimitReached) return response; }