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.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 {/*www . j  ava2 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:tetujin.nikeapi.core.JNikeLowLevelAPI.java

/**
 * /*from w  w  w .  j  a v  a2  s.c  om*/
 * @param strURL ?URL
 * @return jsonStr JSON??
 */
protected String sendHttpRequest(final String strURL) {
    String jsonStr = "";
    try {
        URL url = new URL(strURL);
        /*---------make and set HTTP header-------*/
        //HttpsURLConnection baseConnection = (HttpsURLConnection)url.openConnection();
        HttpsURLConnection con = setHttpHeader((HttpsURLConnection) url.openConnection());

        /*---------show HTTP header information-------*/
        System.out.println("\n ---------http header---------- ");
        Map headers = con.getHeaderFields();
        for (Object key : headers.keySet()) {
            System.out.println(key + ": " + headers.get(key));
        }
        con.connect();

        /*---------get HTTP body information---------*/
        String contentType = con.getHeaderField("Content-Type");
        //String charSet = "Shift-JIS";// "ISO-8859-1";
        String charSet = "UTF-8";// "ISO-8859-1";
        for (String elm : contentType.replace(" ", "").split(";")) {
            if (elm.startsWith("charset=")) {
                charSet = elm.substring(8);
                break;
            }
        }

        /*---------show HTTP body information----------*/
        BufferedReader br;
        try {
            br = new BufferedReader(new InputStreamReader(con.getInputStream(), charSet));
        } catch (Exception e_) {
            System.out.println(con.getResponseCode() + " " + con.getResponseMessage());
            br = new BufferedReader(new InputStreamReader(con.getErrorStream(), charSet));
        }
        System.out.println("\n ---------show HTTP body information----------");
        String line = "";
        while ((line = br.readLine()) != null) {
            jsonStr += line;
        }
        br.close();
        con.disconnect();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(jsonStr);
    return jsonStr;
}

From source file:org.transitime.custom.missionBay.SfmtaApiCaller.java

/**
 * Posts the JSON string to the URL. For either the telemetry or the stop
 * command.//from   ww w . j av  a  2s  .  co m
 * 
 * @param baseUrl
 * @param jsonStr
 * @return True if successfully posted the data
 */
private static boolean post(String baseUrl, String jsonStr) {
    try {
        // Create the connection
        URL url = new URL(baseUrl);
        HttpsURLConnection con = (HttpsURLConnection) url.openConnection();

        // Set parameters for the connection
        con.setRequestMethod("POST");
        con.setRequestProperty("content-type", "application/json");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        // API now uses basic authentication
        String authString = login.getValue() + ":" + password.getValue();
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
        String authStringEnc = new String(authEncBytes);
        con.setRequestProperty("Authorization", "Basic " + authStringEnc);

        // Set the timeout so don't wait forever (unless timeout is set to 0)
        int timeoutMsec = timeout.getValue();
        con.setConnectTimeout(timeoutMsec);
        con.setReadTimeout(timeoutMsec);

        // Write the json data to the connection
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(jsonStr);
        wr.flush();
        wr.close();

        // Get the response
        int responseCode = con.getResponseCode();

        // If wasn't successful then log the response so can debug
        if (responseCode != 200) {
            String responseStr = "";
            if (responseCode != 500) {
                // Response code indicates there was a problem so get the
                // reply in case API returned useful error message
                InputStream inputStream = con.getErrorStream();
                if (inputStream != null) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
                    String inputLine;
                    StringBuffer response = new StringBuffer();
                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    responseStr = response.toString();
                }
            }

            // Lot that response code indicates there was a problem
            logger.error(
                    "Bad HTTP response {} when writing data to SFMTA "
                            + "API. Response text=\"{}\" URL={} json=\n{}",
                    responseCode, responseStr, baseUrl, jsonStr);
        }

        // Done so disconnect just for the heck of it
        con.disconnect();

        // Return whether was successful
        return responseCode == 200;
    } catch (IOException e) {
        logger.error("Exception when writing data to SFMTA API: \"{}\" " + "URL={} json=\n{}", e.getMessage(),
                baseUrl, jsonStr);

        // Return that was unsuccessful
        return false;
    }

}

From source file:org.wso2.carbon.identity.authenticator.PushResult.java

/**
 * validate push result//from w w w  .j  av a 2  s  .c  o m
 */
public JSONObject checkPushResult(String userId, String sessionId) throws AuthenticationFailedException {
    String urlParameters = null;
    JSONObject json = null;
    HttpsURLConnection conn = null;
    InputStream is = null;
    try {
        urlParameters = "action=checkPushResult" + "&serviceId="
                + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId="
                + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&sessionId="
                + URLEncoder.encode(sessionId, InweboConstants.ENCODING) + "&format=json";
        if (this.context == null) {
            this.context = PushAuthentication.setHttpsClientCert(this.p12file, this.p12password);
        }
        SSLSocketFactory sslsocketfactory = context.getSocketFactory();
        URL url = new URL(urlString + urlParameters);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setSSLSocketFactory(sslsocketfactory);
        conn.setRequestMethod("GET");
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is, InweboConstants.ENCODING));
        JSONParser parser = new JSONParser();
        json = (JSONObject) parser.parse(br);
    } catch (UnsupportedEncodingException e) {
        throw new AuthenticationFailedException("Error while encoding the URL" + e.getMessage(), e);
    } catch (MalformedURLException e) {
        throw new AuthenticationFailedException("Error while creating the URL" + e.getMessage(), e);
    } catch (IOException e) {
        throw new AuthenticationFailedException("Error while creating the connection" + e.getMessage(), e);
    } catch (ParseException e) {
        throw new AuthenticationFailedException("Error while parsing the json object" + e.getMessage(), e);
    } catch (Exception e) {
        throw new AuthenticationFailedException("Error while pushing authentication" + e.getMessage(), e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            throw new AuthenticationFailedException("Error while closing stream" + e.getMessage(), e);
        }
    }
    return json;
}

From source file:com.adobe.ibm.watson.traits.impl.WatsonServiceClient.java

/**
 * Fetches the IBM Watson Personal Insights report using the user's Twitter Timeline.
 * @param language/*w ww  .j  ava2s .c  o  m*/
 * @param tweets
 * @param resource
 * @return
 * @throws Exception
 */
public String getWatsonScore(String language, String tweets, Resource resource) throws Exception {

    HttpsURLConnection connection = null;

    // Check if the username and password have been injected to the service.
    // If not, extract them from the cloud service configuration attached to the page.
    if (this.username == null || this.password == null) {
        getWatsonCloudSettings(resource);
    }

    // Build the request to IBM Watson.
    log.info("The Base Url is: " + this.baseUrl);
    String encodedCreds = getBasicAuthenticationEncoding();
    URL url = new URL(this.baseUrl + "/v2/profile");

    connection = (HttpsURLConnection) url.openConnection();
    connection.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestProperty("Accept", "application/json");
    connection.setRequestProperty("Content-Language", language);
    connection.setRequestProperty("Accept-Language", "en-us");
    connection.setRequestProperty("Content-Type", ContentType.TEXT_PLAIN.toString());
    connection.setRequestProperty("Authorization", "Basic " + encodedCreds);
    connection.setUseCaches(false);
    connection.getOutputStream().write(tweets.getBytes());
    connection.getOutputStream().flush();
    connection.connect();

    log.info("Parsing response from Watson");
    StringBuilder str = new StringBuilder();

    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    String line = "";
    while ((line = br.readLine()) != null) {
        str.append(line + System.getProperty("line.separator"));
    }

    if (connection.getResponseCode() != 200) {
        // The call failed, throw an exception.
        log.error(connection.getResponseCode() + " : " + connection.getResponseMessage());
        connection.disconnect();
        throw new Exception("IBM Watson Server responded with an error: " + connection.getResponseMessage());
    } else {
        connection.disconnect();
        return str.toString();
    }
}

From source file:org.schabi.newpipe.Downloader.java

/** AsyncTask impl: executed in background thread does the download */
@Override//ww w . j  a va2  s. c  o  m
protected Void doInBackground(Void... voids) {
    HttpsURLConnection con = null;
    InputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        con = NetCipher.getHttpsURLConnection(fileURL);
        int responseCode = con.getResponseCode();

        // always check HTTP response code first
        if (responseCode == HttpURLConnection.HTTP_OK) {
            fileSize = con.getContentLength();
            inputStream = new BufferedInputStream(con.getInputStream());
            outputStream = new FileOutputStream(saveFilePath);

            int bufferSize = 8192;
            int downloaded = 0;

            int bytesRead = -1;
            byte[] buffer = new byte[bufferSize];
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
                downloaded += bytesRead;
                if (downloaded % 50000 < bufferSize) {
                    publishProgress(downloaded);
                }
            }

            publishProgress(bufferSize);

        } else {
            Log.i(TAG, "No file to download. Server replied HTTP code: " + responseCode);
        }
    } catch (IOException e) {
        Log.e(TAG, "No file to download. Server replied HTTP code: ", e);
        e.printStackTrace();
    } finally {
        try {
            if (outputStream != null) {
                outputStream.close();
                outputStream = null;
            }
            if (inputStream != null) {
                inputStream.close();
                inputStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (con != null) {
            con.disconnect();
            con = null;
        }
    }
    return null;
}

From source file:org.whispersystems.signalservice.internal.push.PushServiceSocket.java

private void uploadAttachment(String method, String url, InputStream data, long dataSize, byte[] key,
        ProgressListener listener) throws IOException {
    URL uploadUrl = new URL(url);
    HttpsURLConnection connection = (HttpsURLConnection) uploadUrl.openConnection();
    connection.setDoOutput(true);//  w  w  w .  j ava 2s. c o m

    if (dataSize > 0) {
        connection
                .setFixedLengthStreamingMode((int) AttachmentCipherOutputStream.getCiphertextLength(dataSize));
    } else {
        connection.setChunkedStreamingMode(0);
    }

    connection.setRequestMethod(method);
    connection.setRequestProperty("Content-Type", "application/octet-stream");
    connection.setRequestProperty("Connection", "close");
    connection.connect();

    try {
        OutputStream stream = connection.getOutputStream();
        AttachmentCipherOutputStream out = new AttachmentCipherOutputStream(key, stream);
        byte[] buffer = new byte[4096];
        int read, written = 0;

        while ((read = data.read(buffer)) != -1) {
            out.write(buffer, 0, read);
            written += read;

            if (listener != null) {
                listener.onAttachmentProgress(dataSize, written);
            }
        }

        data.close();
        out.flush();
        out.close();

        if (connection.getResponseCode() != 200) {
            throw new IOException(
                    "Bad response: " + connection.getResponseCode() + " " + connection.getResponseMessage());
        }
    } finally {
        connection.disconnect();
    }
}

From source file:io.teak.sdk.Session.java

private void startHeartbeat() {
    final Session _this = this;

    this.heartbeatService = Executors.newSingleThreadScheduledExecutor();
    this.heartbeatService.scheduleAtFixedRate(new Runnable() {
        public void run() {
            if (Teak.isDebug) {
                Log.v(LOG_TAG, "Sending heartbeat for user: " + userId);
            }//from   w  w  w  . j a  va 2s  . c o  m

            HttpsURLConnection connection = null;
            try {
                String queryString = "game_id=" + URLEncoder.encode(_this.appConfiguration.appId, "UTF-8")
                        + "&api_key=" + URLEncoder.encode(_this.userId, "UTF-8") + "&sdk_version="
                        + URLEncoder.encode(Teak.SDKVersion, "UTF-8") + "&sdk_platform="
                        + URLEncoder.encode(_this.deviceConfiguration.platformString, "UTF-8") + "&app_version="
                        + URLEncoder.encode(String.valueOf(_this.appConfiguration.appVersion), "UTF-8")
                        + (_this.countryCode == null ? ""
                                : "&country_code="
                                        + URLEncoder.encode(String.valueOf(_this.countryCode), "UTF-8"))
                        + "&buster=" + URLEncoder.encode(UUID.randomUUID().toString(), "UTF-8");
                URL url = new URL("https://iroko.gocarrot.com/ping?" + queryString);
                connection = (HttpsURLConnection) url.openConnection();
                connection.setRequestProperty("Accept-Charset", "UTF-8");
                connection.setUseCaches(false);

                int responseCode = connection.getResponseCode();
                if (Teak.isDebug) {
                    Log.v(LOG_TAG, "Heartbeat response code: " + responseCode);
                }
            } catch (Exception e) {
                Log.e(LOG_TAG, Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
        }
    }, 0, 1, TimeUnit.MINUTES); // TODO: If RemoteConfiguration specifies a different rate, use that
}

From source file:com.wwpass.connection.WWPassConnection.java

private InputStream makeRequest(String method, String command, Map<String, ?> parameters)
        throws IOException, WWPassProtocolException {
    String commandUrl = SpfeURL + command + ".xml";
    //String command_url = SpfeURL + command + ".json";

    StringBuilder sb = new StringBuilder();
    URLCodec codec = new URLCodec();

    @SuppressWarnings("unchecked")
    Map<String, Object> localParams = (Map<String, Object>) parameters;

    for (Map.Entry<String, Object> entry : localParams.entrySet()) {
        sb.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        sb.append("=");
        if (entry.getValue() instanceof String) {
            sb.append(URLEncoder.encode((String) entry.getValue(), "UTF-8"));
        } else {/*from  ww  w . j  a  va 2 s  . com*/
            sb.append(new String(codec.encode((byte[]) entry.getValue())));
        }
        sb.append("&");
    }
    String paramsString = sb.toString();
    sb = null;
    if ("GET".equalsIgnoreCase(method)) {
        commandUrl += "?" + paramsString;
    } else if ("POST".equalsIgnoreCase(method)) {

    } else {
        throw new IllegalArgumentException("Method " + method + " not supported.");
    }

    HttpsURLConnection conn = null;
    try {
        URL url = new URL(commandUrl);
        conn = (HttpsURLConnection) url.openConnection();
        conn.setReadTimeout(timeoutMs);
        conn.setSSLSocketFactory(SPFEContext.getSocketFactory());
        if ("POST".equalsIgnoreCase(method)) {
            conn.setDoOutput(true);
            OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(paramsString);
            writer.flush();
        }
        InputStream in = conn.getInputStream();
        return getReplyData(in);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("Command-parameters combination is invalid: " + e.getMessage());
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
}