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: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", "");
        ;//from  ww w  . ja va 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:com.starr.smartbuilds.service.DataService.java

public void getItemsDataFromRiotAPI() throws IOException, ParseException {
    String line;//ww  w.  ja  v  a 2 s .co m
    String result = "";
    URL url = new URL("https://global.api.pvp.net/api/lol/static-data/euw/v1.2/item?itemListData=tags&api_key="
            + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getItemsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

public void getChampionsDataFromRiotAPI() throws IOException, ParseException {
    String line;/*from  w ww  .j av a  2  s. c om*/
    String result = "";
    URL url = new URL(
            "https://global.api.pvp.net/api/lol/static-data/euw/v1.2/champion?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    getChampionsFromData(result);
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerIdDataFromRiotAPI(String region, String summonerName)
        throws MalformedURLException, IOException, ParseException {
    String line;/*from   ww  w .  j av a 2  s  .  c om*/
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v1.4/summoner/by-name/"
            + summonerName + "?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

From source file:com.starr.smartbuilds.service.DataService.java

private String getSummonerDataFromRiotAPI(String region, Long summonerID)
        throws MalformedURLException, IOException {
    String line;//from   w w  w.j  av a 2 s. c  o m
    String result = "";
    URL url = new URL("https://" + region + ".api.pvp.net/api/lol/" + region + "/v2.5/league/by-summoner/"
            + summonerID + "/entry?api_key=" + Constants.API_KEY);
    //Get connection
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod("GET");

    int responseCode = conn.getResponseCode();
    System.out.println("resp:" + responseCode);
    System.out.println("resp msg:" + conn.getResponseMessage());

    BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    System.out.println("BUFFER----");
    while ((line = br.readLine()) != null) {
        result += line;
    }

    conn.disconnect();
    return result;
}

From source file:in.rab.ordboken.NeClient.java

private String fetchMainSitePage(String pageUrl) throws IOException, LoginException, ParserException {
    URL url = new URL(pageUrl);
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setInstanceFollowRedirects(false);
    urlConnection.connect();//  w  ww  .  j  a v a  2s.  c  om

    int response;

    try {
        response = urlConnection.getResponseCode();
    } catch (IOException e) {
        urlConnection.disconnect();
        throw e;
    }

    if (response == 302) {
        urlConnection.disconnect();

        try {
            loginMainSite();
        } catch (EOFException e) {
            // Same EOFException as on token refreshes. Seems to be a POST thing.
            loginMainSite();
        }

        url = new URL(pageUrl);
        urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setInstanceFollowRedirects(false);
        urlConnection.connect();

        try {
            response = urlConnection.getResponseCode();
        } catch (IOException e) {
            urlConnection.disconnect();
            throw e;
        }
    }

    try {
        if (response != 200) {
            throw new ParserException("Unable to get page: " + response);
        }

        return inputStreamToString(urlConnection.getInputStream());
    } finally {
        urlConnection.disconnect();
    }
}

From source file:org.wso2.carbon.identity.authenticator.smsotp.SMSOTPAuthenticator.java

/**
 * Send REST call/* w w  w  .  j  ava2 s .com*/
 */
public boolean sendRESTCall(String url, String urlParameters) throws IOException {
    HttpsURLConnection connection = null;
    try {
        URL smsProviderUrl = new URL(url + urlParameters);
        connection = (HttpsURLConnection) smsProviderUrl.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(SMSOTPConstants.HTTP_METHOD);
        if (connection.getResponseCode() == 200) {
            if (log.isDebugEnabled()) {
                log.debug("Code is successfully sent to your mobile number");
            }
            return true;
        }
        connection.disconnect();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.error("Invalid URL", e);
        }
        throw new MalformedURLException();
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while setting the HTTP method", e);
        }
        throw new ProtocolException();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.error("Error while getting the HTTP response", e);
        }
        throw new IOException();
    } finally {
        connection.disconnect();
    }
    return false;
}

From source file:com.vmware.o11n.plugin.crypto.service.CryptoCertificateService.java

/**
 * Returns the certificate chain provided by the HTTPS server.
 *
 * The first certificate identifies the server.
 * The remainder should verify the cert upto a trusted root.
 *
 *
 * @param url//from  ww  w .j  a v  a  2s .c  o m
 * @return
 * @throws IOException
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
public List<X509Certificate> getCertHttps(URL url)
        throws IOException, KeyManagementException, NoSuchAlgorithmException {
    ArrayList<X509Certificate> toReturn = new ArrayList<>();

    // Setup a temp ssl context that accepts all certificates for this connection
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        private X509Certificate[] certToReturn;

        @Override
        public void checkClientTrusted(X509Certificate[] c, String s) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] c, String s) {
            certToReturn = c;
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return certToReturn;
        }
    } }, null);

    //Setup a temp hostname verifier that verifies all hostnames for this connection
    HostnameVerifier hv = new HostnameVerifier() {
        @Override
        public boolean verify(String s, SSLSession ss) {
            return true;
        }
    };
    HttpsURLConnection httpsConn = null;
    try {
        httpsConn = (HttpsURLConnection) url.openConnection();

        httpsConn.setSSLSocketFactory(sslContext.getSocketFactory());
        httpsConn.setHostnameVerifier(hv);
        httpsConn.connect();

        Certificate[] certs = httpsConn.getServerCertificates();

        for (Certificate cert : certs) {
            if (cert instanceof X509Certificate) {
                toReturn.add((X509Certificate) cert);
            }
        }
    } finally {
        if (httpsConn != null) {
            httpsConn.disconnect();
        }
    }
    return toReturn;
}

From source file:com.microsoft.onenote.pickerlib.ApiRequestAsyncTask.java

private JSONObject getJSONResponse(String endpoint) throws Exception {
    HttpsURLConnection mUrlConnection = (HttpsURLConnection) (new URL(endpoint)).openConnection();
    mUrlConnection.setRequestProperty("User-Agent",
            System.getProperty("http.agent") + " Android OneNotePicker");
    if (mAccessToken != null) {
        mUrlConnection.setRequestProperty("Authorization", "Bearer " + mAccessToken);
    }/*from w  w  w.  ja va2  s  .  c  o  m*/
    mUrlConnection.connect();

    int responseCode = mUrlConnection.getResponseCode();
    String responseMessage = mUrlConnection.getResponseMessage();
    String responseBody = null;
    boolean responseIsJson = mUrlConnection.getContentType().contains("application/json");
    JSONObject responseObject;
    if (responseCode == HttpsURLConnection.HTTP_UNAUTHORIZED) {
        mUrlConnection.disconnect();
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Invalid or missing access token.", null);
    }
    if (responseIsJson) {
        InputStream is = null;
        try {
            if (responseCode == HttpsURLConnection.HTTP_INTERNAL_ERROR) {
                is = mUrlConnection.getErrorStream();
            } else {
                is = mUrlConnection.getInputStream();
            }
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            String line = null;
            String lineSeparator = System.getProperty("line.separator");
            StringBuffer buffer = new StringBuffer();
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
                buffer.append(lineSeparator);
            }
            responseBody = buffer.toString();
        } finally {
            if (is != null) {
                is.close();
            }
            mUrlConnection.disconnect();
        }

        responseObject = new JSONObject(responseBody);
    } else {
        throw new ApiException(Integer.toString(responseCode) + " " + responseMessage, null,
                "Unrecognized server response", null);
    }

    return responseObject;
}

From source file:org.jembi.rhea.rapidsms.GenerateORU_R01Alert.java

public String callQueryFacility(String msg)
        throws IOException, TransformerFactoryConfigurationError, TransformerException {

    // Setup connection
    URL url = new URL(hostname + "/ws/rest/v1/alerts");
    System.out.println("full url " + url);
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setDoOutput(true);//w w  w  . ja  v  a 2  s  .co  m
    conn.setRequestMethod("POST");
    conn.setDoInput(true);

    // This is important to get the connection to use our trusted
    // certificate
    conn.setSSLSocketFactory(sslFactory);

    addHTTPBasicAuthProperty(conn);
    // conn.setConnectTimeout(timeOut);
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    log.error("body" + msg);
    out.write(msg);
    out.close();
    conn.connect();

    // Test response code
    if (conn.getResponseCode() != 200) {
        throw new IOException(conn.getResponseMessage());
    }

    String result = convertInputStreamToString(conn.getInputStream());
    conn.disconnect();

    return result;
}