Example usage for javax.net.ssl HttpsURLConnection disconnect

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

Introduction

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

Prototype

public abstract void disconnect();

Source Link

Document

Indicates that other requests to the server are unlikely in the near future.

Usage

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void putGetFileExample() throws Exception {
    HttpsURLConnection connection;
    String redirect;//w  w w .  j  av  a 2s  . com
    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:org.wso2.iot.firealarm.access.api.AccessTokenClient.java

public AccessTokenInfo getAccessToken(String username, String password, String appInstanceId)
        throws AccessTokenException {
    SSLContext ctx;/*from www  .j  a  v  a  2  s.  c  o m*/
    String response = "";
    try {
        ctx = SSLContext.getInstance("TLS");

        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        SSLContext.setDefault(ctx);

        URL url = new URL(tokenURL);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
        //System.out.println(conn.getResponseCode());
        conn.disconnect();

        HttpClient httpClient = new HttpClient();

        PostMethod postMethod = new PostMethod(tokenURL);
        postMethod.addParameter(new NameValuePair("grant_type", grantType));
        postMethod.addParameter(new NameValuePair("username", username));
        postMethod.addParameter(new NameValuePair("password", password));
        postMethod.addParameter(new NameValuePair("scope", scope + appInstanceId));

        postMethod.addRequestHeader("Authorization", "Basic " + appToken);
        postMethod.addRequestHeader("Content-Type", "application/x-www-form-urlencoded");

        httpClient.executeMethod(postMethod);

        response = postMethod.getResponseBodyAsString();
        log.info(response);
        JSONObject jsonObject = new JSONObject(response);

        AccessTokenInfo accessTokenInfo = new AccessTokenInfo();
        accessTokenInfo.setAccess_token(jsonObject.getString("access_token"));
        accessTokenInfo.setRefresh_token(jsonObject.getString("refresh_token"));
        accessTokenInfo.setExpires_in(jsonObject.getInt("expires_in"));
        accessTokenInfo.setToken_type(jsonObject.getString("token_type"));

        return accessTokenInfo;

    } catch (NoSuchAlgorithmException | KeyManagementException | IOException | JSONException e) {
        log.error(e.getMessage());
        throw new AccessTokenException("Configuration Error for Access Token Generation");
    } catch (NullPointerException e) {

        return null;
    }

}

From source file:no.digipost.android.api.ApiAccess.java

public static void uploadFile(Context context, String uri, File file) throws DigipostClientException {
    try {//w  ww .j  a v  a2 s.  com
        try {

            FileBody filebody = new FileBody(file, ApiConstants.CONTENT_OCTET_STREAM);
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName(ApiConstants.ENCODING));
            multipartEntity.addPart("subject", new StringBody(FilenameUtils.removeExtension(file.getName()),
                    ApiConstants.MIME, Charset.forName(ApiConstants.ENCODING)));
            multipartEntity.addPart("file", filebody);
            multipartEntity.addPart("token", new StringBody(TokenStore.getAccess()));

            URL url = new URL(uri);
            HttpsURLConnection httpsClient = (HttpsURLConnection) url.openConnection();
            httpsClient.setRequestMethod("POST");
            httpsClient.setDoOutput(true);
            if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                httpsClient.setFixedLengthStreamingMode(multipartEntity.getContentLength());
            } else {
                httpsClient.setChunkedStreamingMode(0);
            }
            httpsClient.setRequestProperty("Connection", "Keep-Alive");
            httpsClient.addRequestProperty("Content-length", multipartEntity.getContentLength() + "");
            httpsClient.setRequestProperty(ApiConstants.AUTHORIZATION,
                    ApiConstants.BEARER + TokenStore.getAccess());
            httpsClient.addRequestProperty(multipartEntity.getContentType().getName(),
                    multipartEntity.getContentType().getValue());

            try {
                OutputStream outputStream = new BufferedOutputStream(httpsClient.getOutputStream());
                multipartEntity.writeTo(outputStream);
                outputStream.flush();
                NetworkUtilities.checkHttpStatusCode(context, httpsClient.getResponseCode());
            } finally {
                httpsClient.disconnect();
            }

        } catch (DigipostInvalidTokenException e) {
            OAuth.updateAccessTokenWithRefreshToken(context);
            uploadFile(context, uri, file);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, context.getString(R.string.error_your_network));
        throw new DigipostClientException(context.getString(R.string.error_your_network));
    }
}

From source file:mediasearch.twitter.TwitterService.java

private String requestBearerToken() {
    HttpsURLConnection connection = basicAuthConnectionPost(TwitterData.OAUTH_TOKEN_URL);

    JSONObject obj = (JSONObject) JSONValue.parse(readResponse(connection));
    if (obj != null) {
        String tokenType = (String) obj.get("token_type");
        String token = (String) obj.get("access_token");
        return ((tokenType.equals("bearer")) && (token != null)) ? token : "";
    }//from www  .j  a va  2 s.  co m

    if (connection != null) {
        connection.disconnect();
    }
    return null;
}

From source file:com.hybris.mobile.data.WebServiceDataProvider.java

/**
 * Synchronous call for logging in//  ww w. j a  v a 2  s .com
 * 
 * @param httpBody
 * @return The data from the server as a string, in almost all cases JSON
 * @throws MalformedURLException
 * @throws IOException
 * @throws JSONException
 */
public static String getLoginResponse(Bundle httpBody) throws MalformedURLException, IOException {
    String response = "";
    URL url = new URL(WebServiceAuthProvider.tokenURL());
    trustAllHosts();
    HttpsURLConnection connection = createSecureConnection(url);
    connection.setHostnameVerifier(DO_NOT_VERIFY);
    String authString = "mobile_android:secret";
    String authValue = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    connection.setRequestMethod("POST");
    connection.setRequestProperty("Authorization", authValue);
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.connect();

    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 (MalformedURLException e) {
        LoggingUtils.e(LOG_TAG,
                "Error reading stream \"" + connection.getInputStream() + "\". " + e.getLocalizedMessage(),
                null);
    } catch (IOException e) {
        response = readFromStream(connection.getErrorStream());
    } finally {
        connection.disconnect();
    }

    return response;
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.HTTPSConnectionAndTrustConfirmationIT.java

@Test
public void testTrustConfirmationProvidersTrustNever() 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();//from ww w.ja  va 2  s . 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
    } finally {
        conn.disconnect();
    }

    // Add the trust confirmation provider that trusts no one
    List<TrustConfirmationProvider> trustProviders = new ArrayList<TrustConfirmationProvider>();
    credentialManager.setTrustConfirmationProviders(trustProviders);
    trustProviders = new ArrayList<TrustConfirmationProvider>();
    trustProviders.add(new TrustNeverTrustConfimationProvider());
    credentialManager.setTrustConfirmationProviders(trustProviders);

    HttpsURLConnection conn2 = (HttpsURLConnection) url.openConnection();
    try {
        // This should still fail as our trust providers are not trusting anyone
        // and we have not added heater's certificate to Credential Manager's Truststore
        conn2.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 {
        conn2.disconnect();
    }
}

From source file:it.bz.tis.integreen.carsharingbzit.api.ApiClient.java

public <T> T callWebService(ServiceRequest request, Class<T> clazz) throws IOException {

    request.request.technicalUser.username = this.user;
    request.request.technicalUser.password = this.password;

    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE)
            .setVisibility(PropertyAccessor.IS_GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.GETTER, Visibility.PUBLIC_ONLY)
            .setVisibility(PropertyAccessor.SETTER, Visibility.PUBLIC_ONLY);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, request);//  w w w.java2 s .com

    String requestJson = sw.getBuffer().toString();

    logger.debug("callWebService(): jsonRequest:" + requestJson);

    URL url = new URL(this.endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoOutput(true);
    OutputStream out = conn.getOutputStream();
    out.write(requestJson.getBytes("UTF-8"));
    out.flush();
    int responseCode = conn.getResponseCode();

    InputStream input = conn.getInputStream();

    ByteArrayOutputStream data = new ByteArrayOutputStream();
    int len;
    byte[] buf = new byte[50000];
    while ((len = input.read(buf)) > 0) {
        data.write(buf, 0, len);
    }
    conn.disconnect();
    String jsonResponse = new String(data.toByteArray(), "UTF-8");

    if (responseCode != 200) {
        throw new IOException(jsonResponse);
    }

    logger.debug("callWebService(): jsonResponse:" + jsonResponse);

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    T response = mapper.readValue(new StringReader(jsonResponse), clazz);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    sw = new StringWriter();
    mapper.writeValue(sw, response);
    logger.debug(
            "callWebService(): parsed response into " + response.getClass().getName() + ":" + sw.toString());

    return response;
}

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();/*from  w  w w  . j  a  v  a  2  s . c o 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
    } 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.raphfrk.craftproxyclient.net.auth.AuthManager.java

public static JSONObject sendRequest(JSONObject request, String endpoint) {
    URL url;/*from  www.  j av a2 s .  co m*/
    try {
        url = new URL(authServer + "/" + endpoint);
    } catch (MalformedURLException e) {
        return null;
    }
    try {
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setInstanceFollowRedirects(false);
        con.setReadTimeout(5000);
        con.setConnectTimeout(5000);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/json");
        con.connect();

        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
        try {
            request.writeJSONString(writer);
            writer.flush();
            writer.close();

            if (con.getResponseCode() != 200) {
                return null;
            }

            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
            try {
                JSONParser parser = new JSONParser();

                try {
                    return (JSONObject) parser.parse(reader);
                } catch (ParseException e) {
                    return null;
                }
            } finally {
                reader.close();
            }
        } finally {
            writer.close();
            con.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }

}

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();/*from w  ww.j  av a  2 s  . c om*/

    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();
}