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:com.camel.trainreserve.JDKHttpsClient.java

public static String doGet(String url) {
    InputStream in = null;//from   w  w  w.j  av  a 2s.c  o m
    BufferedReader br = null;
    StringBuffer str_return = new StringBuffer();
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new java.security.SecureRandom());
        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.connect();
        in = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(in));
        String line = null;
        while ((line = br.readLine()) != null) {
            str_return = str_return.append(line);
        }
        conn.disconnect();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            br.close();
            in.close();
        } catch (Exception e) {
        }
    }
    return str_return.toString();
}

From source file:com.camel.trainreserve.JDKHttpsClient.java

public static ByteArrayOutputStream doGetImg(String url, String cookieStr) {
    InputStream in = null;/*from   w w  w  . j a va  2 s .  c om*/
    ByteArrayOutputStream outStream = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());

        URL console = new URL(url);
        HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
        conn.setRequestProperty("Cookie", cookieStr);
        conn.setSSLSocketFactory(sc.getSocketFactory());
        conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
        conn.connect();
        in = conn.getInputStream();
        outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = in.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        conn.disconnect();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) {
        }
    }
    return outStream;
}

From source file:com.clearcenter.mobile_demo.mdRest.java

static private StringBuffer ProcessRequest(HttpsURLConnection http) throws IOException {
    http.connect();//from w w  w  .  j a va2 s. c om

    Log.d(TAG, "Result code: " + http.getResponseCode() + ", content type: " + http.getContentType()
            + ", content length: " + http.getContentLength());

    // Read response, 8K buffer
    BufferedReader buffer = new BufferedReader(new InputStreamReader(http.getInputStream()), 8192);

    String data;
    StringBuffer response = new StringBuffer();
    while ((data = buffer.readLine()) != null)
        response.append(data);

    Log.d(TAG, "Response buffer length: " + response.length());

    buffer.close();
    http.disconnect();

    return response;
}

From source file:com.rmtheis.yandtran.YandexTranslatorAPI.java

/**
 * Forms an HTTPS request, sends it using GET method and returns the result of the request as a String.
 * //from w w w . j  ava2  s.c om
 * @param url The URL to query for a String response.
 * @return The translated String.
 * @throws Exception on error.
 */
private static String retrieveResponse(final URL url) throws Exception {
    final HttpsURLConnection uc = (HttpsURLConnection) url.openConnection();
    if (referrer != null)
        uc.setRequestProperty("referer", referrer);
    uc.setRequestProperty("Content-Type", "text/plain; charset=" + ENCODING);
    uc.setRequestProperty("Accept-Charset", ENCODING);
    uc.setRequestMethod("GET");

    try {
        final int responseCode = uc.getResponseCode();
        final String result = inputStreamToString(uc.getInputStream());
        if (responseCode != 200) {
            throw new Exception("Error from Yandex API: " + result);
        }
        return result;
    } finally {
        if (uc != null) {
            uc.disconnect();
        }
    }
}

From source file:org.kuali.mobility.push.service.send.AndroidSendService.java

/**
 * Writes the data over the connection// w  ww. j av a 2 s.c  o  m
 * @param conn
 * @param data
 * @return
 * @throws java.net.MalformedURLException
 * @throws java.io.IOException
 */
private static String sendToGCM(HttpsURLConnection conn, String data) throws IOException {
    byte[] dataBytes = data.getBytes();
    conn.setFixedLengthStreamingMode(dataBytes.length);
    OutputStream out = null;
    String response = null;
    try {
        out = conn.getOutputStream();
        out.write(dataBytes);
        out.flush();
        response = readResponse(conn);

    } catch (IOException e) {
        LOG.warn("Exception while trying to write data to GCM", e);
    } finally {
        IOUtils.closeQuietly(out);
        conn.disconnect();
    }
    return response;
}

From source file:mediasearch.twitter.TwitterService.java

private ArrayList<TwitterTweet> searchForTweetsAndParseJson(String query) throws UnsupportedEncodingException {
    final String q = TwitterData.SEARCH_URL + URLEncoder.encode(query, "UTF-8");
    HttpsURLConnection connection = bearerAuthConnectionGet(q);
    if (connection != null) {
        connection.disconnect();
    }/*  www . ja v  a 2  s.co m*/

    String readResponse = readResponse(connection);
    JSONObject obj = (JSONObject) JSONValue.parse(readResponse);
    return parseJsonIntoTweets(obj);
}

From source file:com.raphfrk.craftproxyclient.net.auth.AuthManager.java

@SuppressWarnings("unchecked")
public static void authServer17(String hash) throws IOException {
    URL url;/*from www.j a va2  s  .  c o  m*/
    String username;
    String accessToken;
    try {
        if (loginDetails == null) {
            throw new IOException("Not logged in");
        }

        try {
            username = URLEncoder.encode(getUsername(), "UTF-8");
            accessToken = URLEncoder.encode(getAccessToken(), "UTF-8");
            hash = URLEncoder.encode(hash, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IOException("Username/password encoding error", e);
        }

        String urlString;
        urlString = sessionServer17;
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        throw new IOException("Auth server URL error", e);
    }
    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();

    JSONObject obj = new JSONObject();
    obj.put("accessToken", accessToken);
    obj.put("selectedProfile", loginDetails.get("selectedProfile"));
    obj.put("serverId", hash);
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(con.getOutputStream(), StandardCharsets.UTF_8));
    try {
        obj.writeJSONString(writer);
        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (writer != null) {
            writer.close();
            con.disconnect();
            return;
        }
    }
    if (con.getResponseCode() != 200) {
        throw new IOException("Unable to verify username, please restart proxy");
    }
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8));
    try {
        String reply = reader.readLine();
        if (reply != null) {
            throw new IOException("Auth server replied (" + reply + ")");
        }
    } finally {
        reader.close();
        con.disconnect();
    }
}

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

public static HttpsResponse getRequest(String Uri, String requestParameters) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;/*from w w  w. j  a  v a  2  s .  c o  m*/
        if (requestParameters != null && requestParameters.length() > 0) {
            urlStr += "?" + requestParameters;
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        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) {
        } catch (IOException ignored) {
        } finally {
            if (rd != null) {
                rd.close();
            }
            conn.disconnect();
        }
        return new HttpsResponse(sb.toString(), conn.getResponseCode());
    }
    return null;
}

From source file:org.apache.hadoop.hdfsproxy.ProxyUtil.java

static void checkServerCertsExpirationDays(Configuration conf, String hostname, int port) throws IOException {
    setupSslProps(conf);//from ww  w  .  j  av  a 2s  .com
    HttpsURLConnection connection = null;
    connection = openConnection(hostname, port, null);
    connection.connect();
    X509Certificate[] serverCerts = (X509Certificate[]) connection.getServerCertificates();
    Date curDate = new Date();
    long curTime = curDate.getTime();
    if (serverCerts != null) {
        for (X509Certificate cert : serverCerts) {
            StringBuffer sb = new StringBuffer();
            sb.append("\n Server certificate Subject Name: " + cert.getSubjectX500Principal().getName());
            Date expDate = cert.getNotAfter();
            long expTime = expDate.getTime();
            int dayOffSet = (int) ((expTime - curTime) / MM_SECONDS_PER_DAY);
            sb.append(" have " + dayOffSet + " days to expire");
            if (dayOffSet < CERT_EXPIRATION_WARNING_THRESHOLD)
                LOG.warn(sb.toString());
            else
                LOG.info(sb.toString());
        }
    } else {
        LOG.info("\n No Server certs was found");
    }

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

From source file:net.minder.KnoxWebHdfsJavaClientExamplesTest.java

@Test
public void getHomeDirExample() throws Exception {
    HttpsURLConnection connection;
    InputStream input;/*from   w  w  w . ja v a2s.  c o  m*/
    JsonNode json;

    connection = createHttpUrlConnection(WEBHDFS_URL + "?op=GETHOMEDIRECTORY");
    input = connection.getInputStream();
    json = MAPPER.readTree(input);
    input.close();
    connection.disconnect();
    assertThat(json.get("Path").asText(), is("/user/" + TEST_USERNAME));

}