List of usage examples for javax.net.ssl HttpsURLConnection getHeaderField
public String getHeaderField(int n)
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 av a 2 s . c o 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:org.aankor.animenforadio.api.WebsiteGate.java
private void updateCookies(HttpsURLConnection con) { Pattern titlePattern = Pattern.compile("PHPSESSID=([^;]*);"); Matcher matcher = titlePattern.matcher(con.getHeaderField("Set-Cookie")); if (matcher.find()) phpSessID = matcher.group(1);//from w w w .ja v a 2 s . co m }
From source file:com.bytelightning.opensource.pokerface.HelloWorldScriptTest.java
@Test public void testHelloWorld() throws IOException { URL obj = new URL("https://localhost:8443/helloWorlD.html"); // Intentional case mismatch HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Accept-Language", "es, fr;q=0.8, en;q=0.7"); int responseCode = con.getResponseCode(); Assert.assertEquals("Valid reponse code", 200, responseCode); String contentType = con.getHeaderField("Content-Type"); String charset = ScriptHelperImpl.GetCharsetFromContentType(contentType); Assert.assertTrue("Correct charset", charset.equalsIgnoreCase("utf-8")); try (Reader reader = new InputStreamReader(con.getInputStream(), charset)) { int aChar; StringBuilder sb = new StringBuilder(); while ((aChar = reader.read()) != -1) sb.append((char) aChar); Assert.assertTrue("Acceptable language detected", sb.toString().contains("Hola mundo")); }/* w ww .j ava 2 s . c o m*/ }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java
@Test public void testTrustConfirmationProvidersTrustAlways() throws IOException, CMException { // Initially trust provider list is empty, we only verify by what is in // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/) // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory credentialManager.initializeSSL();//ww w .j a v a2s . co m URL url = new URL("https://heater.cs.man.ac.uk:7443/"); HttpsURLConnection conn; conn = (HttpsURLConnection) url.openConnection(); try { // This should fail conn.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good System.out.println(sslex.getStackTrace()); } finally { conn.disconnect(); } // Add the trust confirmation provider that trusts everyone List<TrustConfirmationProvider> trustProviders = new ArrayList<TrustConfirmationProvider>(); trustProviders.add(new TrustAlwaysTrustConfirmationProvider()); credentialManager.setTrustConfirmationProviders(trustProviders); HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection(); // This should work now conn2.connect(); System.out.println("Status header: " + conn2.getHeaderField(0)); assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0)); conn2.disconnect(); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java
@Test @Ignore//from w w w.j av a2 s. c o 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:com.clearcenter.mobile_demo.mdRest.java
static public String GetSystemInfo(String host, String token, long last_sample) throws JSONException, ParseException, IOException, AuthenticationException { try {/*from w w w.j av a 2 s.c om*/ URL url = new URL("https://" + host + URL_SYSINFO + "/" + last_sample); Log.v(TAG, "GetSystemInfo: host: " + host + ", token: " + token + ", URL: " + url); HttpsURLConnection http = CreateConnection(url); http.setRequestMethod("GET"); http.setRequestProperty("Cookie", token); final StringBuffer response = ProcessRequest(http); // Process response JSONObject json_data = null; try { //Log.i(TAG, "response: " + response.toString()); json_data = new JSONObject(response.toString()); } catch (JSONException e) { Log.e(TAG, "JSONException", e); return ""; } if (json_data.has("result")) { Integer result = RESULT_UNKNOWN; try { result = Integer.valueOf(json_data.getString("result")); } catch (NumberFormatException e) { } Log.d(TAG, "result: " + result.toString()); if (result == RESULT_SUCCESS && json_data.has("data")) { //Log.i(TAG, "data: " + json_data.getString("data")); return json_data.getString("data"); } if (result == RESULT_ACCESS_DENIED) throw new AuthenticationException(); // New cookies? final String cookie = http.getHeaderField("Set-Cookie"); if (cookie != null) { Log.d(TAG, "New cookie!"); } // All other results are failures... throw new IOException(); } } catch (MalformedURLException e) { Log.e(TAG, "MalformedURLException", e); throw new ParseException(); } Log.i(TAG, "Malformed result"); throw new IOException(); }
From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java
@Test public void putGetFileExample() throws Exception { HttpsURLConnection connection; String redirect;//w w w . ja va2 s . c o m InputStream input; OutputStream output; String data = UUID.randomUUID().toString(); connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=CREATE"); connection.setRequestMethod("PUT"); assertThat(connection.getResponseCode(), is(307)); redirect = connection.getHeaderField("Location"); connection.disconnect(); connection = createHttpUrlConnection(redirect); connection.setRequestMethod("PUT"); connection.setDoOutput(true); output = connection.getOutputStream(); IOUtils.write(data.getBytes(), output); output.close(); connection.disconnect(); assertThat(connection.getResponseCode(), is(201)); connection = createHttpUrlConnection(WEBHDFS_URL + "/tmp/" + data + "/?op=OPEN"); assertThat(connection.getResponseCode(), is(307)); redirect = connection.getHeaderField("Location"); connection.disconnect(); connection = createHttpUrlConnection(redirect); input = connection.getInputStream(); assertThat(IOUtils.toString(input), is(data)); input.close(); connection.disconnect(); }
From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java
@Test public void testTrustConfirmationAddDeleteCertificateDirectly() throws CMException, IOException, CertificateException { // Initially trust provider list is empty, we only verify by what is in // Credential Manager's Truststore (and it does not contains the certificate for https://heater.cs.man.ac.uk:7443/) // Do not forget to initialise Taverna's/Credential Manager's SSLSocketFactory credentialManager.initializeSSL();//w w w. ja va 2 s .com URL url = new URL("https://heater.cs.man.ac.uk:7443/"); HttpsURLConnection conn; conn = (HttpsURLConnection) url.openConnection(); try { // This should fail conn.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good } finally { conn.disconnect(); } // Add heater's certificate directly to Credential Manager's Truststore // Load the test trusted certificate (belonging to heater.cs.man.ac.uk) X509Certificate trustedCertficate; URL trustedCertficateFileURL = getClass().getResource("/security/tomcat_heater_certificate.pem"); System.out.println("testTrustConfirmationAddDeleteCertificateDirectly: trusted certficate file URL " + trustedCertficateFileURL); File trustedCertFile = new File(trustedCertficateFileURL.getPath()); FileInputStream inStream = new FileInputStream(trustedCertFile); //InputStream inStream = getClass().getClassLoader().getResourceAsStream("security/tomcat_heater_certificate.pem"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); trustedCertficate = (X509Certificate) certFactory.generateCertificate(inStream); try { inStream.close(); } catch (Exception e) { // Ignore } String alias = credentialManager.addTrustedCertificate(trustedCertficate); HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection(); // This should work now conn2.connect(); //System.out.println(conn2.getHeaderField(0)); assertEquals("HTTP/1.1 200 OK", conn2.getHeaderField(0)); conn2.disconnect(); // Now remove certificate and see if the "trust" changes credentialManager.deleteTrustedCertificate(alias); HttpsURLConnection conn3; conn3 = (HttpsURLConnection) url.openConnection(); try { // This should fail conn3.connect(); fail("Connection to https://heater.cs.man.ac.uk:7443/ should be untrusted at this point."); } catch (SSLHandshakeException sslex) { // expected to fail so all is good } finally { conn3.disconnect(); } }
From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java
private static HttpCookie getTmCookie(final String url, final String username, final String password, final int timeout) throws IOException { if (tmCookie != null && !tmCookie.hasExpired()) { return tmCookie; }//from ww w .j a v a 2 s. com final String charset = UTF8_STR; final String query = String.format("u=%s&p=%s", URLEncoder.encode(username, charset), URLEncoder.encode(password, charset)); final URLConnection connection = new URL(url).openConnection(); if (!(connection instanceof HttpsURLConnection)) { return null; } final HttpsURLConnection http = (HttpsURLConnection) connection; http.setInstanceFollowRedirects(false); http.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); http.setRequestMethod("POST"); http.setAllowUserInteraction(true); if (timeout != 0) { http.setConnectTimeout(timeout); http.setReadTimeout(timeout); } http.setDoOutput(true); // Triggers POST. http.setRequestProperty("Accept-Charset", charset); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); OutputStream output = null; try { output = http.getOutputStream(); output.write(query.getBytes(charset)); } finally { if (output != null) { try { output.close(); } catch (IOException e) { LOGGER.debug(e, e); } } } LOGGER.info("fetching cookie: " + url); connection.connect(); tmCookie = HttpCookie.parse(http.getHeaderField("Set-Cookie")).get(0); LOGGER.debug("cookie: " + tmCookie); return tmCookie; }
From source file:com.clearcenter.mobile_demo.mdRest.java
static public String Login(String host, String username, String password, String token) throws JSONException { if (password == null) Log.i(TAG, "Login by cookie, host: " + host + ", username: " + username); else/*from w w w.j a v a 2s. c om*/ Log.i(TAG, "Login by password, host: " + host + ", username: " + username); try { URL url = new URL("https://" + host + URL_LOGIN); HttpsURLConnection http = CreateConnection(url); if (password != null) { // Setup HTTPS POST request String urlParams = "username=" + URLEncoder.encode(username, "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&submit=submit"; http.setRequestMethod("POST"); http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); http.setRequestProperty("Content-Length", Integer.toString(urlParams.getBytes().length)); // Write request DataOutputStream outputStream = new DataOutputStream(http.getOutputStream()); outputStream.writeBytes(urlParams); outputStream.flush(); outputStream.close(); } else { http.setRequestMethod("GET"); http.setRequestProperty("Cookie", token); } final StringBuffer response = ProcessRequest(http); // Process response JSONObject json_data = null; try { Log.i(TAG, "response: " + response.toString()); json_data = new JSONObject(response.toString()); } catch (JSONException e) { Log.e(TAG, "JSONException", e); return ""; } if (json_data.has("result")) { final String cookie = http.getHeaderField("Set-Cookie"); Integer result = RESULT_UNKNOWN; try { result = Integer.valueOf(json_data.getString("result")); } catch (NumberFormatException e) { } Log.i(TAG, "result: " + result.toString() + ", cookie: " + cookie); if (result == RESULT_SUCCESS) { if (cookie != null) return cookie; else return token; } // All other results are failures... return ""; } } catch (Exception e) { Log.e(TAG, "Exception", e); } Log.i(TAG, "Malformed result"); return ""; }