Example usage for javax.net.ssl HttpsURLConnection setAllowUserInteraction

List of usage examples for javax.net.ssl HttpsURLConnection setAllowUserInteraction

Introduction

In this page you can find the example usage for javax.net.ssl HttpsURLConnection setAllowUserInteraction.

Prototype

public void setAllowUserInteraction(boolean allowuserinteraction) 

Source Link

Document

Set the value of the allowUserInteraction field of this URLConnection .

Usage

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static String fetchSecureContent(final String url, final int timeout) throws IOException {
    LOGGER.info("fetchSecureContent: " + url);
    final URL u = new URL(url);
    final URLConnection conn = u.openConnection();
    if (timeout != 0) {
        conn.setConnectTimeout(timeout);
        conn.setReadTimeout(timeout);/*from w  ww.  j ava2  s.  c o  m*/
    }
    if (conn instanceof HttpsURLConnection) {
        final HttpsURLConnection http = (HttpsURLConnection) conn;
        http.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(final String arg0, final SSLSession arg1) {
                return true;
            }
        });
        http.setRequestMethod(GET_STR);
        http.setAllowUserInteraction(true);
    }
    return IOUtils.toString(conn.getInputStream());
}

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 w w w  .  ja  v  a  2  s .co m*/

    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.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadFile(final String url) throws IOException {
    InputStream in = null;/*from ww w  .  jav a  2s .co m*/
    OutputStream out = null;
    try {
        LOGGER.info("downloadFile: " + url);
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();
        if (urlc instanceof HttpsURLConnection) {
            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
        }
        in = urlc.getInputStream();//new GZIPInputStream(dbURL.openStream());
        //      if(sourceCompressed) { in = new GZIPInputStream(in); }

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:com.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadTM(final String url, final String authUrl, final String username,
        final String password, final int timeout) throws IOException {
    InputStream in = null;//from   w w w  .  j a va2  s  .  c  o  m
    OutputStream out = null;

    try {
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();

        if (timeout != 0) {
            urlc.setConnectTimeout(timeout);
            urlc.setReadTimeout(timeout);
        }

        if (urlc instanceof HttpsURLConnection) {
            final String cookie = getTmCookie(authUrl, username, password, timeout).toString();

            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
            http.addRequestProperty("Cookie", cookie);
        }

        in = urlc.getInputStream();

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:org.wso2.carbon.automation.test.utils.http.client.HttpsURLConnectionClient.java

public static HttpsResponse deleteWithBasicAuth(String uri, String contentType, String userName,
        String password) throws IOException {
    if (uri.startsWith("https://")) {
        URL url = new URL(uri);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("DELETE");
        String encode = new String(
                new org.apache.commons.codec.binary.Base64().encode((userName + ":" + password).getBytes()))
                        .replaceAll("\n", "");
        ;// ww  w . j  a  v a  2 s  .co  m
        conn.setRequestProperty("Authorization", "Basic " + encode);
        if (contentType != null) {
            conn.setRequestProperty("Content-Type", contentType);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        conn.connect();
        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:Activities.java

private String addData(String endpoint) {
    String data = null;/*from  w w w  .java  2 s.c  o  m*/
    try {
        // Construct request payload
        JSONObject attrObj = new JSONObject();
        attrObj.put("name", "URL");
        attrObj.put("value", "http://www.nvidia.com/game-giveaway");

        JSONArray attrArray = new JSONArray();
        attrArray.add(attrObj);

        TimeZone tz = TimeZone.getTimeZone("UTC");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'");
        df.setTimeZone(tz);
        String dateAsISO = df.format(new Date());

        // Required attributes
        JSONObject obj = new JSONObject();
        obj.put("leadId", "1001");
        obj.put("activityDate", dateAsISO);
        obj.put("activityTypeId", "1001");
        obj.put("primaryAttributeValue", "Game Giveaway");
        obj.put("attributes", attrArray);
        System.out.println(obj);

        // Make request
        URL url = new URL(endpoint);
        HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();
        urlConn.setRequestMethod("POST");
        urlConn.setAllowUserInteraction(false);
        urlConn.setDoOutput(true);
        urlConn.setRequestProperty("Content-type", "application/json");
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.connect();
        OutputStream os = urlConn.getOutputStream();
        os.write(obj.toJSONString().getBytes());
        os.close();

        // Inspect response
        int responseCode = urlConn.getResponseCode();
        if (responseCode == 200) {
            System.out.println("Status: 200");
            InputStream inStream = urlConn.getInputStream();
            data = convertStreamToString(inStream);
            System.out.println(data);
        } else {
            System.out.println(responseCode);
            data = "Status:" + responseCode;
        }
    } catch (MalformedURLException e) {
        System.out.println("URL not valid.");
    } catch (IOException e) {
        System.out.println("IOException: " + e.getMessage());
        e.printStackTrace();
    }

    return data;
}

From source file:it.serverSystem.HttpsTest.java

private void connectUntrusted() throws Exception {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from  w  w w.j a  va 2 s.  c o  m*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Install the all-trusting trust manager
    // SSLv3 is disabled since SQ 4.5.2 : https://jira.codehaus.org/browse/SONAR-5860
    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());

    SSLSocketFactory untrustedSocketFactory = sc.getSocketFactory();

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    URL url = new URL("https://localhost:" + httpsPort + "/sessions/login");
    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setAllowUserInteraction(true);
    connection.setSSLSocketFactory(untrustedSocketFactory);
    connection.setHostnameVerifier(allHostsValid);

    InputStream input = connection.getInputStream();
    checkCookieFlags(connection);
    try {
        String html = IOUtils.toString(input);
        assertThat(html).contains("<body");
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:com.persistent.cloudninja.scheduler.DeploymentMonitor.java

/**
 * Gets the information regarding the roles and their instances
 * of the deployment. It makes a call to REST API and gets the XML response. 
 * //from  w w w . j a v a 2 s  .  c om
 * @return XML response
 * @throws IOException
 */
public StringBuffer getRoleInfoForDeployment() throws IOException {
    StringBuffer response = new StringBuffer();
    System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");

    StringBuffer keyStore = new StringBuffer();
    keyStore.append(System.getProperty("java.home"));
    LOGGER.debug("java.home : " + keyStore.toString());
    if (keyStore.length() == 0) {
        keyStore.append(System.getenv("JRE_HOME"));
        LOGGER.debug("JRE_HOME : " + keyStore.toString());
    }
    keyStore.append(File.separator + "lib\\security\\CloudNinja.pfx");
    System.setProperty("javax.net.ssl.keyStore", keyStore.toString());
    System.setProperty("javax.net.debug", "ssl");
    System.setProperty("javax.net.ssl.keyStorePassword", keyStorePassword);
    System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);

    SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    // form the URL which will return the response
    // containing info of roles and their instances.
    StringBuffer strURL = new StringBuffer(host);
    strURL.append(subscriptionId);
    strURL.append("/services/hostedservices/");
    strURL.append(hostedServiceName);
    strURL.append("/deploymentslots/");
    strURL.append(deploymentType);

    URL url = new URL(strURL.toString());

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
    connection.setSSLSocketFactory(sslSocketFactory);
    connection.setRequestMethod("GET");
    connection.setAllowUserInteraction(false);
    // set the x-ms-version in header which is a compulsory parameter to get response 
    connection.setRequestProperty("x-ms-version", "2011-10-01");
    connection.setRequestProperty("Content-type", "text/xml");
    connection.setRequestProperty("accept", "text/xml");
    // get the response as input stream
    InputStream inputStream = connection.getInputStream();
    InputStreamReader streamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(streamReader);
    String string = null;
    while ((string = bufferedReader.readLine()) != null) {
        response.append(string);
    }
    return response;
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *//*from  w w  w.j  a  v  a 2  s.  co  m*/
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        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());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}