Example usage for javax.net.ssl HttpsURLConnection getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void putGetFileExample() throws Exception {
    HttpsURLConnection connection;
    String redirect;//from  w ww  . j a  v a2  s. c om
    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:de.thingweb.client.security.Security4NicePlugfest.java

public Registration requestRegistrationAS() throws IOException {
    String clientName = "opPostmanTestRS"; // CLIENT_NAME_PREFIX +
    // System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"], \"id_token_signed_response_alg\":\"" + "HS256" + "\"}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AS);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();//from  w w  w .  j a v  a2 s .  c  o  m

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisR);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            return new Registration(c_id.textValue(), c_secret.textValue());
        }

    } else {
        // error
        InputStream error = httpConRegistration.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }
    httpConRegistration.disconnect();

    return null;
}

From source file:httpRequests.GetPost.java

private void sendPost() throws Exception {

    String url = "https://selfsolve.apple.com/wcResults.do";
    URL obj = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";

    // Send post request
    con.setDoOutput(true);//from w  w  w .  j  av a2s.  c om
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + url);
    System.out.println("Post parameters : " + urlParameters);
    System.out.println("Response Code : " + responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    //print result
    System.out.println(response.toString());

}

From source file:de.thingweb.client.security.Security4NicePlugfest.java

public Registration requestRegistrationAM() throws IOException {

    Registration registration = null;/*w w  w  .j a  v  a2s.c o  m*/

    String clientName = CLIENT_NAME_PREFIX + System.currentTimeMillis();
    String clientCredentials = "client_credentials";
    String requestBodyRegistration = "{\"client_name\": \"" + clientName + "\",\"grant_types\": [\""
            + clientCredentials + "\"]}";

    // Registration
    URL urlRegistration = new URL(HTTPS_PREFIX + HOST + REQUEST_REGISTRATION_AM);

    HttpsURLConnection httpConRegistration = (HttpsURLConnection) urlRegistration.openConnection();
    httpConRegistration.setDoOutput(true);
    httpConRegistration.setRequestProperty("Host", REQUEST_HEADER_HOST);
    httpConRegistration.setRequestProperty("Content-Type", "application/json");
    httpConRegistration.setRequestProperty("Accept", "application/json");
    httpConRegistration.setRequestMethod("POST");

    OutputStream outRegistration = httpConRegistration.getOutputStream();
    outRegistration.write(requestBodyRegistration.getBytes());
    outRegistration.close();

    int responseCodeRegistration = httpConRegistration.getResponseCode();
    log.info("responseCode Registration for " + urlRegistration + ": " + responseCodeRegistration);

    if (responseCodeRegistration == 201) {
        // everything ok
        InputStream isR = httpConRegistration.getInputStream();
        byte[] bisR = getBytesFromInputStream(isR);
        String jsonResponseRegistration = new String(bisR);
        log.info(jsonResponseRegistration);

        // extract the value of client_id (this value is called <c_id>in
        // the following) and the value of client_secret (called
        // <c_secret> in the following) from the JSON response

        ObjectMapper mapper = new ObjectMapper();
        JsonFactory factory = mapper.getFactory();
        JsonParser jp = factory.createParser(bisR);
        JsonNode actualObj = mapper.readTree(jp);

        JsonNode c_id = actualObj.get("client_id");
        JsonNode c_secret = actualObj.get("client_secret");

        if (c_id == null || c_id.getNodeType() != JsonNodeType.STRING || c_secret == null
                || c_secret.getNodeType() != JsonNodeType.STRING) {
            log.error("client_id: " + c_id);
            log.error("client_secret: " + c_secret);
        } else {
            // ok so far
            // Store <c_id> and <c_secret> for use during the token
            // acquisition
            log.info("client_id: " + c_id);
            log.info("client_secret: " + c_secret);

            registration = new Registration(c_id.textValue(), c_secret.textValue());
        }

    } else {
        // error
        InputStream error = httpConRegistration.getErrorStream();
        byte[] berror = getBytesFromInputStream(error);
        log.error(new String(berror));
    }
    httpConRegistration.disconnect();

    return registration;
}

From source file:org.jboss.aerogear.adm.AdmService.java

/**
 * Request that ADM deliver your message to a specific instance of your app.
 *
 * @param registrationId representing the unique identifier of the device
 * @param clientId unique ID supplied by ADM Services
 * @param clientSecret secret value supplied by ADM services
 * @param payload , a String representing the complete payload to be submitted
 * @throws Exception if sending the message fails
 *///from   w  ww  .  ja  v  a 2  s . c  o m
public void sendMessageToDevice(final String registrationId, final String clientId, final String clientSecret,
        final String payload) throws Exception {

    if (accessToken == null) {
        accessToken = tokenService.getAuthToken(clientId, clientSecret);
    }

    // Generate the HTTPS connection for the POST request.
    // You cannot make a connection over plain HTTP.
    HttpsURLConnection conn = post(registrationId, payload);

    // Obtain the response code from the connection.
    final int responseCode = conn.getResponseCode();

    // Check if we received a failure response, and if so, get the reason for the failure.
    if (responseCode != 200) {
        if (responseCode == 401) {
            accessToken = tokenService.getAuthToken(clientId, clientSecret);
            sendMessageToDevice(registrationId, clientId, clientSecret, payload);
        } else {
            String errorContent = parseResponse(conn.getErrorStream());
            throw new RuntimeException(String.format("ERROR: The enqueue request failed with a "
                    + "%d response code, with the following message: %s", responseCode, errorContent));
        }

    } else {
        // The request was successful. The response contains the canonical Registration ID for the specific instance of your
        // app, which may be different that the one used for the request.

        final String responseContent = parseResponse(conn.getInputStream());
        final JSONObject parsedObject = new JSONObject(responseContent);

        final String canonicalRegistrationId = parsedObject.getString("registrationID");

        // Check if the two Registration IDs are different.
        if (!canonicalRegistrationId.equals(registrationId)) {
            // At this point the data structure that stores the Registration ID values should be updated
            // with the correct Registration ID for this particular app instance.
        }
    }

}

From source file:de.escidoc.core.test.sb.HttpRequester.java

/**
 * Sends request with given method and given body to given URI and returns result as String.
 *
 * @param resource String resource/*ww  w . j  a  va  2 s  . com*/
 * @param method   String method
 * @param body     String body
 * @return String response
 * @throws Exception e
 */
private String requestSsl(final String resource, final String method, final String body) throws Exception {
    URL url;
    InputStream is = null;
    StringBuffer response = new StringBuffer();

    // Open Connection to given resource
    url = new URL(domain + resource);
    TrustManager[] tm = { new RelaxedX509TrustManager() };
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, tm, new java.security.SecureRandom());
    SSLSocketFactory sslSF = sslContext.getSocketFactory();
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setSSLSocketFactory(sslSF);

    // Set Basic-Authentication Header
    if (securityHandle != null && !securityHandle.equals("")) {
        String encoding = new String(Base64.encodeBase64(securityHandle.getBytes(ClientBase.DEFAULT_CHARSET)));
        con.setRequestProperty("Authorization", "Basic " + encoding);
    }

    // Set request-method and timeout
    con.setRequestMethod(method.toUpperCase(Locale.ENGLISH));
    con.setReadTimeout(TIMEOUT);

    // If PUT or POST, write given body in Output-Stream
    if ((method.equalsIgnoreCase("PUT") || method.equalsIgnoreCase("POST")) && body != null) {
        con.setDoOutput(true);
        OutputStream out = con.getOutputStream();
        out.write(body.getBytes(ClientBase.DEFAULT_CHARSET));
        out.flush();
        out.close();
    }

    // Request
    is = con.getInputStream();

    // Read response
    String currentLine = null;
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    while ((currentLine = br.readLine()) != null) {
        response.append(currentLine + "\n");
    }
    is.close();
    return response.toString();
}

From source file:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java

public String getUserInformation(String username, String password, String accessToken)
        throws AuthenticationFailedException {
    String responseString = "";
    HttpsURLConnection connection = null;
    String authStr = username + ":" + password;
    String encoding = new String(Base64.encodeBase64(authStr.getBytes()));
    try {//from  w  ww.  j av  a2 s.  com
        String query = String.format("access_token=%s", URLEncoder.encode(accessToken, MepinConstants.CHARSET));

        connection = (HttpsURLConnection) new URL(MepinConstants.MEPIN_GET_USER_INFO_URL + "?" + query)
                .openConnection();
        connection.setRequestMethod(MepinConstants.HTTP_GET);
        connection.setRequestProperty(MepinConstants.HTTP_ACCEPT, MepinConstants.HTTP_CONTENT_TYPE);
        connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION,
                MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding);
        int status = connection.getResponseCode();
        if (log.isDebugEnabled()) {
            log.debug("MePIN Response Code :" + status);
        }
        if (status == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
            if (log.isDebugEnabled()) {
                log.debug("MePIN Response :" + responseString);
            }
        } else {
            return MepinConstants.FAILED;
        }

    } catch (IOException e) {
        throw new AuthenticationFailedException(MepinConstants.MEPIN_ID_NOT_FOUND, e);
    } finally {
        connection.disconnect();
    }
    return responseString;
}

From source file:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java

private String postRequest(String url, String query, String username, String password) throws IOException {

    String authStr = username + ":" + password;
    String encoding = new String(Base64.encodeBase64(authStr.getBytes()));
    String responseString = "";
    HttpsURLConnection connection = null;
    BufferedReader br;/*from   w  w  w . jav a 2  s.  c  o m*/
    StringBuilder sb;
    String line;

    try {
        connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty(MepinConstants.HTTP_ACCEPT_CHARSET, MepinConstants.CHARSET);
        connection.setRequestProperty(MepinConstants.HTTP_CONTENT_TYPE, MepinConstants.HTTP_POST_CONTENT_TYPE);
        connection.setRequestProperty(MepinConstants.HTTP_AUTHORIZATION,
                MepinConstants.HTTP_AUTHORIZATION_BASIC + encoding);

        OutputStream output = connection.getOutputStream();
        output.write(query.getBytes(MepinConstants.CHARSET));

        int status = connection.getResponseCode();

        if (log.isDebugEnabled()) {
            log.debug("MePIN Response Code :" + status);
        }
        switch (status) {
        case 200:
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
            break;
        case 201:
        case 400:
        case 403:
        case 404:
        case 500:
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
            if (log.isDebugEnabled()) {
                log.debug("MePIN Response :" + responseString);
            }
            return MepinConstants.FAILED;
        }
    } catch (IOException e) {
        if (connection.getErrorStream() != null) {
            br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line).append("\n");
            }
            br.close();
            responseString = sb.toString();
            if (log.isDebugEnabled()) {
                log.debug("MePIN Response :" + responseString);
            }
            return MepinConstants.FAILED;
        }
    } finally {
        connection.disconnect();
    }
    if (log.isDebugEnabled()) {
        log.debug("MePIN Response :" + responseString);
    }
    return responseString;
}

From source file:org.eclipse.smarthome.binding.digitalstrom.internal.lib.serverconnection.impl.HttpTransportImpl.java

@Override
public String execute(String request, int connectTimeout, int readTimeout) {
    // NOTE: We will only show exceptions in the debug level, because they will be handled in the checkConnection()
    // method and this changes the bridge state. If a command was send it fails than and a sensorJob will be
    // execute the next time, by TimeOutExceptions. By other exceptions the checkConnection() method handles it in
    // max 1 second.
    String response = null;/*from  w w w. j  av a 2 s  .  c om*/
    HttpsURLConnection connection = null;
    try {
        String correctedRequest = checkSessionToken(request);
        connection = getConnection(correctedRequest, connectTimeout, readTimeout);
        if (connection != null) {
            connection.connect();
            final int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_FORBIDDEN) {
                if (responseCode == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                    response = IOUtils.toString(connection.getErrorStream());
                } else {
                    response = IOUtils.toString(connection.getInputStream());
                }
                if (response != null) {
                    if (!response.contains("Authentication failed")) {
                        if (loginCounter > 0) {
                            connectionManager.checkConnection(responseCode);
                        }
                        loginCounter = 0;
                    } else {
                        connectionManager.checkConnection(ConnectionManager.AUTHENTIFICATION_PROBLEM);
                        loginCounter++;
                    }
                }

            }
            connection.disconnect();
            if (response == null && connectionManager != null
                    && loginCounter <= MAY_A_NEW_SESSION_TOKEN_IS_NEEDED) {
                if (responseCode == HttpURLConnection.HTTP_FORBIDDEN) {
                    execute(addSessionToken(correctedRequest, connectionManager.getNewSessionToken()),
                            connectTimeout, readTimeout);
                    loginCounter++;
                } else {
                    connectionManager.checkConnection(responseCode);
                    loginCounter++;
                    return null;
                }
            }
            return response;
        }
    } catch (SocketTimeoutException e) {
        informConnectionManager(ConnectionManager.SOCKET_TIMEOUT_EXCEPTION);
    } catch (java.net.ConnectException e) {
        informConnectionManager(ConnectionManager.CONNECTION_EXCEPTION);
    } catch (MalformedURLException e) {
        informConnectionManager(ConnectionManager.MALFORMED_URL_EXCEPTION);
    } catch (java.net.UnknownHostException e) {
        informConnectionManager(ConnectionManager.UNKNOWN_HOST_EXCEPTION);
    } catch (IOException e) {
        logger.error("An IOException occurred: ", e);
        if (connectionManager != null) {
            informConnectionManager(ConnectionManager.GENERAL_EXCEPTION);
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
    return null;
}

From source file:gov.nih.nci.cabig.ccts.security.SecureURL.java

/**
 * Retrieve the contents from the given URL as a String, assuming the URL's
 * server matches what we expect it to match.
 *///from  ww  w  .  j  a v a 2 s  . com
public static String retrieve(String url) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("entering retrieve(" + url + ")");
    }
    BufferedReader r = null;
    try {
        URL u = new URL(url);
        if (!u.getProtocol().equals("https")) {
            // IOException may not be the best exception we could throw here
            // since the problem is with the URL argument we were passed,
            // not
            // IO. -awp9
            log.error("retrieve(" + url + ") on an illegal URL since protocol was not https.");
            throw new IOException("only 'https' URLs are valid for this method");
        }

        // JAP: changing to allow validation of Globus-style host names.
        // URLConnection uc = u.openConnection();
        HttpsURLConnection uc = (HttpsURLConnection) u.openConnection();
        uc.setHostnameVerifier(new HostnameVerifier() {

            public boolean verify(String hostname, SSLSession session) {
                boolean valid = false;
                try {
                    String expectedHostname = hostname.toLowerCase();
                    log.debug("expectedHostname = " + expectedHostname);

                    String subjectDN = session.getPeerCertificateChain()[0].getSubjectDN().getName()
                            .toLowerCase();
                    log.debug("subjectDN = " + subjectDN);
                    String assertedHostname = null;
                    for (String part : subjectDN.split(",")) {
                        String[] nameValue = part.split("=");
                        String name = nameValue[0].toLowerCase().trim();
                        String value = nameValue[1].trim();
                        if (name.equals("cn")) {
                            assertedHostname = value;
                            break;
                        }
                    }
                    if (assertedHostname == null) {
                        log.warn("No common name found in subject distinguished name.");
                        return false;
                    }
                    log.debug("assertedHostname = " + assertedHostname);
                    if (assertedHostname.startsWith("host/")) {
                        expectedHostname = "host/" + expectedHostname;
                        log.debug("detected Globus-style common name, expectedHostname = " + expectedHostname);
                    }
                    valid = assertedHostname.equals(expectedHostname);
                    log.debug("valid = " + valid);
                } catch (Exception ex) {
                    log.warn(ex);
                }
                return valid;
            }

        });

        uc.setRequestProperty("Connection", "close");
        r = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line;
        StringBuffer buf = new StringBuffer();
        while ((line = r.readLine()) != null)
            buf.append(line + "\n");
        return buf.toString();
    } finally {
        try {
            if (r != null)
                r.close();
        } catch (IOException ex) {
            // ignore
        }
    }
}