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.liberty.android.fantastischmemo.downloader.quizlet.lib.java

public static String[] getAccessTokens(final String[] requests) throws Exception {
    final String TAG = "getAccesTokens";
    String code = requests[0];// w  w  w.j  a va 2 s.co  m
    String clientIdAndSecret = QUIZLET_CLIENT_ID + ":" + QUIZLET_CLIENT_SECRET;
    String encodedClientIdAndSecret = Base64.encodeToString(clientIdAndSecret.getBytes(), 0);
    URL url1 = new URL("https://api.quizlet.com/oauth/token");
    HttpsURLConnection conn = (HttpsURLConnection) url1.openConnection();
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

    // Add the Basic Authorization item
    conn.addRequestProperty("Authorization", "Basic " + encodedClientIdAndSecret);

    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);
    String payload = String.format("grant_type=%s&code=%s&redirect_uri=%s",
            URLEncoder.encode("authorization_code", "UTF-8"), URLEncoder.encode(code, "UTF-8"),
            URLEncoder.encode(Data.RedirectURI, "UTF-8"));
    OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
    out.write(payload);
    out.close();

    if (conn.getResponseCode() / 100 >= 3) {
        Log.e(TAG, "Http response code: " + conn.getResponseCode() + " response message: "
                + conn.getResponseMessage());
        JsonReader r = new JsonReader(new InputStreamReader(conn.getErrorStream(), "UTF-8"));
        String error = "";
        r.beginObject();
        while (r.hasNext()) {
            error += r.nextName() + r.nextString() + "\r\n";
        }
        r.endObject();
        r.close();
        Log.e(TAG, "Error response for: " + url1 + " is " + error);
        throw new IOException("Response code: " + conn.getResponseCode());
    }

    JsonReader s = new JsonReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
    try {
        String accessToken = null;
        String userId = null;
        s.beginObject();
        while (s.hasNext()) {
            String name = s.nextName();
            if (name.equals("access_token")) {
                accessToken = s.nextString();
            } else if (name.equals("user_id")) {
                userId = s.nextString();
            } else {
                s.skipValue();
            }
        }
        s.endObject();
        s.close();
        return new String[] { accessToken, userId };
    } catch (Exception e) {
        // Throw out JSON exception. it is unlikely to happen
        throw new RuntimeException(e);
    } finally {
        conn.disconnect();
    }
}

From source file:com.longtime.ajy.support.weixin.HttpsKit.java

/**
 * ??Post/* w w w .j av  a 2  s  .  com*/
 * 
 * @param url
 * @param params
 * @return
 * @throws IOException
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
public static String post(String url, String params) {//throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {

    OutputStream out = null;
    InputStream in = null;
    HttpsURLConnection http = null;
    try {
        StringBuffer bufferRes = null;
        TrustManager[] tm = { new MyX509TrustManager() };
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // SSLContextSSLSocketFactory  
        SSLSocketFactory ssf = sslContext.getSocketFactory();

        URL urlGet = new URL(url);
        http = (HttpsURLConnection) urlGet.openConnection();
        // 
        http.setConnectTimeout(TIME_OUT_CONNECT);
        // ? --??
        http.setReadTimeout(TIME_OUT_READ);
        http.setRequestMethod("POST");
        http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        http.setSSLSocketFactory(ssf);
        http.setDoOutput(true);
        http.setDoInput(true);
        http.connect();

        out = http.getOutputStream();
        out.write(params.getBytes("UTF-8"));
        out.flush();

        in = http.getInputStream();
        BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
        String valueString = null;
        bufferRes = new StringBuffer();
        while ((valueString = read.readLine()) != null) {
            bufferRes.append(valueString);
        }

        return bufferRes.toString();

    } catch (Exception e) {
        logger.error(String.format("HTTP POST url=[%s] param=[%s] due to fail.", url, params), e);
    } finally {

        if (null != out) {
            try {
                out.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s]  close outputstream due to fail.",
                        url, params), e);
            }
        }
        if (null != in) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error(String.format("HTTP POST url=[%s] param=[%s] close inputstream due to fail.", url,
                        params), e);
            }
        }

        if (http != null) {
            // 
            http.disconnect();

        }
    }
    return StringUtils.EMPTY;
}

From source file:Main.java

public static String executeHttpsPost(String url, String data, InputStream key) {
    HttpsURLConnection localHttpsURLConnection = null;
    try {//  w ww .j  a  v a  2s  . c  o  m
        URL localURL = new URL(url);
        localHttpsURLConnection = (HttpsURLConnection) localURL.openConnection();
        localHttpsURLConnection.setRequestMethod("POST");
        localHttpsURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        localHttpsURLConnection.setRequestProperty("Content-Length",
                "" + Integer.toString(data.getBytes().length));
        localHttpsURLConnection.setRequestProperty("Content-Language", "en-US");

        localHttpsURLConnection.setUseCaches(false);
        localHttpsURLConnection.setDoInput(true);
        localHttpsURLConnection.setDoOutput(true);

        localHttpsURLConnection.connect();
        Certificate[] arrayOfCertificate = localHttpsURLConnection.getServerCertificates();

        byte[] arrayOfByte1 = new byte[294];
        DataInputStream localDataInputStream = new DataInputStream(key);
        localDataInputStream.readFully(arrayOfByte1);
        localDataInputStream.close();

        Certificate localCertificate = arrayOfCertificate[0];
        PublicKey localPublicKey = localCertificate.getPublicKey();
        byte[] arrayOfByte2 = localPublicKey.getEncoded();

        for (int i = 0; i < arrayOfByte2.length; i++) {
            if (arrayOfByte2[i] != arrayOfByte1[i])
                throw new RuntimeException("Public key mismatch");
        }

        DataOutputStream localDataOutputStream = new DataOutputStream(
                localHttpsURLConnection.getOutputStream());
        localDataOutputStream.writeBytes(data);
        localDataOutputStream.flush();
        localDataOutputStream.close();

        InputStream localInputStream = localHttpsURLConnection.getInputStream();
        BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localInputStream));

        StringBuffer localStringBuffer = new StringBuffer();
        String str1;
        while ((str1 = localBufferedReader.readLine()) != null) {
            localStringBuffer.append(str1);
            localStringBuffer.append('\r');
        }
        localBufferedReader.close();

        return localStringBuffer.toString();
    } catch (Exception localException) {
        byte[] arrayOfByte1;
        localException.printStackTrace();
        return null;
    } finally {
        if (localHttpsURLConnection != null)
            localHttpsURLConnection.disconnect();
    }
}

From source file:pack_test.Get_stream.java

/**
 * Run the web service request//from   ww w.  j a va 2s  . c  om
 */
//public static void main(String[] args) {
public void main() {
    HttpsURLConnection conn = null;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL(
                "https://devicecloud.digi.com/ws/v1/streams/history/00000000-00000000-00409DFF-FF6064F8/xbee.analog/[00:13:A2:00:40:E6:5A:88]!/AD1");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        System.out.println(responseContent);
    } catch (Exception e) {
        // Print any exceptions that occur
        e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

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

/**
 * Prompt for a login and an OTP./* w w  w  .j av a 2s  . com*/
 */
public JSONObject pushAuthenticate(String userId) throws AuthenticationFailedException {
    String urlParameters = null;
    JSONObject json = null;
    HttpsURLConnection conn = null;
    InputStream is = null;
    try {
        urlParameters = "action=pushAuthenticate" + "&serviceId="
                + URLEncoder.encode("" + serviceId, InweboConstants.ENCODING) + "&userId="
                + URLEncoder.encode(userId, InweboConstants.ENCODING) + "&format=json";
        if (this.context == null) {
            this.context = 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 (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:br.com.intelidev.dao.userDao.java

/**
  * Run the web service request/*  w  w  w .j  av  a  2  s.co  m*/
  * @param username
  * @param password
  * @return 
  */
public boolean login_acess(String username, String password) {
    HttpsURLConnection conn = null;
    boolean bo_return = false;

    try {
        // Create url to the Device Cloud server for a given web service request
        URL url = new URL("https://devicecloud.digi.com/ws/sci");
        conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("GET");

        // Build authentication string
        String userpassword = username + ":" + password;

        // can change this to use a different base64 encoder
        String encodedAuthorization = Base64.encodeBase64String(userpassword.getBytes()).trim();

        // set request headers
        conn.setRequestProperty("Authorization", "Basic " + encodedAuthorization);
        // Get input stream from response and convert to String
        InputStream is = conn.getInputStream();

        Scanner isScanner = new Scanner(is);
        StringBuffer buf = new StringBuffer();
        while (isScanner.hasNextLine()) {
            buf.append(isScanner.nextLine() + "\n");
        }
        //String responseContent = buf.toString();

        // add line returns between tags to make it a bit more readable
        //responseContent = responseContent.replaceAll("><", ">\n<");

        // Output response to standard out
        //System.out.println(responseContent);
        bo_return = true;
    } catch (Exception e) {
        // Print any exceptions that occur
        System.out.println("br.com.intelidev.dao.userDao.login_acess() Error: " + e);
        bo_return = false;
        //e.printStackTrace();
    } finally {
        if (conn != null)
            conn.disconnect();
        if (bo_return) {
            System.out.println("Conectou ");
        } else {
            System.out.println("No conectou ");
        }

    }
    return bo_return;
}

From source file:com.glaf.core.util.http.HttpUtils.java

/**
 * ?https?/*from  ww w  . j  a  v a2 s  .com*/
 * 
 * @param requestUrl
 *            ?
 * @param method
 *            ?GET?POST
 * @param content
 *            ???
 * @return
 */
public static String doRequest(String requestUrl, String method, String content, boolean isSSL) {
    log.debug("requestUrl:" + requestUrl);
    HttpsURLConnection conn = null;
    InputStream inputStream = null;
    BufferedReader bufferedReader = null;
    InputStreamReader inputStreamReader = null;
    StringBuffer buffer = new StringBuffer();
    try {
        URL url = new URL(requestUrl);
        conn = (HttpsURLConnection) url.openConnection();
        if (isSSL) {
            // SSLContext??
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // SSLContextSSLSocketFactory
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            conn.setSSLSocketFactory(ssf);
        }
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        // ?GET/POST
        conn.setRequestMethod(method);
        if ("GET".equalsIgnoreCase(method)) {
            conn.connect();
        }

        // ????
        if (StringUtils.isNotEmpty(content)) {
            OutputStream outputStream = conn.getOutputStream();
            // ????
            outputStream.write(content.getBytes("UTF-8"));
            outputStream.flush();
            outputStream.close();
        }

        // ???
        inputStream = conn.getInputStream();
        inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        bufferedReader = new BufferedReader(inputStreamReader);

        String str = null;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
        }

        log.debug("response:" + buffer.toString());

    } catch (ConnectException ce) {
        ce.printStackTrace();
        log.error(" http server connection timed out.");
    } catch (Exception ex) {
        ex.printStackTrace();
        log.error("http request error:{}", ex);
    } finally {
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(bufferedReader);
        IOUtils.closeQuietly(inputStreamReader);
        if (conn != null) {
            conn.disconnect();
        }
    }
    return buffer.toString();
}

From source file:org.schabi.newpipe.download.FileDownloader.java

/** AsyncTask impl: executed in background thread does the download */
@Override//www . j av a  2  s  . c om
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();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (con != null) {
            con.disconnect();
        }
    }
    return null;
}

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 2s. c o m
    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:org.wso2.carbon.identity.authenticator.mepin.MepinTransactions.java

protected String getTransaction(String url, String transactionId, String clientId, String username,
        String password) throws IOException {

    log.debug("Started handling transaction creation");
    String authStr = username + ":" + password;
    String encoding = new String(Base64.encodeBase64(authStr.getBytes()));
    HttpsURLConnection connection = null;
    String responseString = "";

    url = url + "?transaction_id=" + transactionId + "&client_id=" + clientId;
    try {/* www  .j  a v  a2s .  co m*/
        connection = (HttpsURLConnection) new URL(url).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);

        String response = "";
        int statusCode = connection.getResponseCode();
        InputStream is;
        if ((statusCode == 200) || (statusCode == 201)) {
            is = connection.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String output;
            while ((output = br.readLine()) != null) {
                responseString += output;
            }
            br.close();
        } else {
            is = connection.getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String output;
            while ((output = br.readLine()) != null) {
                responseString += output;
            }
            br.close();
            if (log.isDebugEnabled()) {
                log.debug("MePIN Status Response: " + response);
            }
            return MepinConstants.FAILED;
        }

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