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.emuneee.nctrafficcams.tasks.GetLatestCameras.java

private String getLatestUpdateTime() {
    HttpsURLConnection connection = null;
    BufferedReader reader = null;
    String updateDatetime = null;

    try {//from  w w w  .  j ava  2 s  .  com
        StringBuilder updateStr = new StringBuilder();
        connection = HttpUtils.getAuthUrlConnection(mBaseUrl + sUpdatePath, mContext);
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line = null;

        while ((line = reader.readLine()) != null) {
            updateStr.append(line);
        }
        Log.d(TAG, "Content Size: " + updateStr.length());
        Log.d(TAG, "Response Code: " + connection.getResponseCode());
        JSONObject updateObj = new JSONObject(updateStr.toString());
        updateDatetime = updateObj.getString("updated");
    } catch (Exception e) {
        Log.e(TAG, "Error getting latest update time");
        Log.e(TAG, e.getMessage());
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                Log.w(TAG, "Error retrieving latest update time");
                Log.w(TAG, e.getMessage());
            }
        }
    }

    return updateDatetime;
}

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

private void loginMainSite() throws IOException, LoginException {
    ArrayList<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();

    data.add(new BasicNameValuePair("_save_loginForm", "true"));
    data.add(new BasicNameValuePair("redir", "/success"));
    data.add(new BasicNameValuePair("redirFail", "/fail"));
    data.add(new BasicNameValuePair("userName", mUsername));
    data.add(new BasicNameValuePair("passWord", mPassword));

    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(data);

    URL url = new URL("https://www.ne.se/user/login.jsp");
    HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
    https.setInstanceFollowRedirects(false);
    https.setFixedLengthStreamingMode((int) entity.getContentLength());
    https.setDoOutput(true);//from   w  w w .  j a  va 2  s.c om

    try {
        OutputStream output = https.getOutputStream();
        entity.writeTo(output);
        output.close();

        Integer response = https.getResponseCode();
        if (response != 302) {
            throw new LoginException("Unexpected response: " + response);
        }

        String location = https.getHeaderField("Location");
        if (!location.contains("/success")) {
            throw new LoginException("Failed to login");
        }
    } finally {
        https.disconnect();
    }
}

From source file:org.wso2.carbon.integration.common.tests.JaggeryServerTest.java

/**
 * Sending the request and getting the response
 * @param Uri - request url//  ww  w.java 2s  . co  m
 * @param append - append request parameters
 * @throws IOException
 */
private HttpsResponse getRequest(String Uri, String requestParameters, boolean append) throws IOException {
    if (Uri.startsWith("https://")) {
        String urlStr = Uri;
        if (requestParameters != null && requestParameters.length() > 0) {
            if (append) {
                urlStr += "?" + requestParameters;
            } else {
                urlStr += requestParameters;
            }
        }
        URL url = new URL(urlStr);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type", "application/json");
        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(), "UTF-8"));
            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:com.versobit.weatherdoge.WeatherUtil.java

private static WeatherResult getWeatherFromYahoo(double latitude, double longitude, String location) {
    try {// w  ww .  jav a 2s. c om
        String yqlText;
        if (latitude == Double.MIN_VALUE && longitude == Double.MIN_VALUE) {
            if (location == null) {
                return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, "No valid location parameters.",
                        new IllegalArgumentException());
            }
            yqlText = location.replaceAll("[^\\p{L}\\p{Nd} ,-]+", "");
        } else {
            yqlText = String.valueOf(latitude) + ", " + String.valueOf(longitude);
        }
        URL url = new URL("https://query.yahooapis.com/v1/public/yql?q=" + URLEncoder.encode(
                "select location.city, units, item.condition, astronomy from weather.forecast where woeid in (select woeid from geo.placefinder where text = \""
                        + yqlText + "\" and gflags = \"R\" limit 1) limit 1",
                "UTF-8") + "&format=json");
        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
        try {
            JSONObject response = new JSONObject(IOUtils.toString(connection.getInputStream()));
            if (connection.getResponseCode() != HttpsURLConnection.HTTP_OK) {
                JSONObject error = response.getJSONObject("error");
                return new WeatherResult(null, WeatherResult.ERROR_API, error.getString("description"), null);
            }
            JSONObject query = response.getJSONObject("query");
            if (query.getInt("count") == 0) {
                return new WeatherResult(null, WeatherResult.ERROR_API, "No results found for that location.",
                        null);
            }

            JSONObject channel = query.getJSONObject("results").getJSONObject("channel");
            JSONObject units = channel.getJSONObject("units");
            JSONObject condition = channel.getJSONObject("item").getJSONObject("condition");
            JSONObject astronomy = channel.getJSONObject("astronomy");

            double temp = condition.getDouble("temp");
            if ("F".equals(units.getString("temperature"))) {
                temp = (temp - 32d) * 5d / 9d;
            }
            String text = condition.getString("text");
            String code = condition.getString("code");
            String date = condition.getString("date");
            String sunrise = astronomy.getString("sunrise");
            String sunset = astronomy.getString("sunset");

            String owmCode = convertYahooCode(code, date, sunrise, sunset);

            if (location == null || location.isEmpty()) {
                location = channel.getJSONObject("location").getString("city");
            }

            return new WeatherResult(new WeatherData(temp, text, owmCode, latitude, longitude, location,
                    new Date(), Source.YAHOO), WeatherResult.ERROR_NONE, null, null);
        } finally {
            connection.disconnect();
        }
    } catch (Exception ex) {
        return new WeatherResult(null, WeatherResult.ERROR_THROWABLE, ex.getMessage(), ex);
    }
}

From source file:org.sufficientlysecure.keychain.ui.linked.LinkedIdCreateGithubFragment.java

private static JSONObject jsonHttpRequest(String url, JSONObject params, String accessToken)
        throws IOException, HttpResultException {

    HttpsURLConnection nection = (HttpsURLConnection) new URL(url).openConnection();
    nection.setDoInput(true);/*  w w  w  .j  a v a  2  s. c  o m*/
    nection.setDoOutput(true);
    nection.setConnectTimeout(2000);
    nection.setReadTimeout(1000);
    nection.setRequestProperty("Content-Type", "application/json");
    nection.setRequestProperty("Accept", "application/json");
    nection.setRequestProperty("User-Agent", "OpenKeychain " + BuildConfig.VERSION_NAME);
    if (accessToken != null) {
        nection.setRequestProperty("Authorization", "token " + accessToken);
    }

    OutputStream os = nection.getOutputStream();
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
    writer.write(params.toString());
    writer.flush();
    writer.close();
    os.close();

    try {

        nection.connect();

        int code = nection.getResponseCode();
        if (code != HttpsURLConnection.HTTP_CREATED && code != HttpsURLConnection.HTTP_OK) {
            throw new HttpResultException(nection.getResponseCode(), nection.getResponseMessage());
        }

        InputStream in = new BufferedInputStream(nection.getInputStream());
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder response = new StringBuilder();
        while (true) {
            String line = reader.readLine();
            if (line == null) {
                break;
            }
            response.append(line);
        }

        try {
            return new JSONObject(response.toString());
        } catch (JSONException e) {
            throw new IOException(e);
        }

    } finally {
        nection.disconnect();
    }

}

From source file:se.leap.bitmaskclient.ProviderAPI.java

private JSONObject getErrorMessage(HttpsURLConnection urlConnection) {
    JSONObject error_message = new JSONObject();
    if (urlConnection != null) {
        InputStream error_stream = urlConnection.getErrorStream();
        if (error_stream != null) {
            String error_response = new Scanner(error_stream).useDelimiter("\\A").next();
            try {
                error_message = new JSONObject(error_response);
            } catch (JSONException e) {
                e.printStackTrace();//from   w w w  .j  a  v a 2  s.c  o  m
            }
            urlConnection.disconnect();
        }
    }
    return error_message;
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {/*  w w w  . j a va 2s  .  c  om*/
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

        return new String[] { code + "", result };
    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callPostAndPut " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callPostAndPut " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:com.microsoft.speech.tts.Authentication.java

private void HttpPost(String AccessTokenUri, String apiKey) {
    InputStream inSt = null;/*from   w  w w . ja  v  a2 s . c  o m*/
    HttpsURLConnection webRequest = null;

    this.accessToken = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("Ocp-Apim-Subscription-Key", apiKey);
        webRequest.setRequestMethod("POST");

        String request = "";
        byte[] bytes = request.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        this.accessToken = strBuffer.toString();

    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}

From source file:android.locationprivacy.algorithm.Webservice.java

@Override
public Location obfuscate(Location location) {
    // We do it this way to run network connection in main thread. This
    // way is not the normal one and does not comply to best practices,
    // but the main thread must wait for the obfuscation service reply anyway.
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);// ww w.  ja  v a 2  s .  c om

    final String HOST_ADDRESS = configuration.getString("host");
    String username = configuration.getString("username");
    String password = configuration.getString("secret_password");

    Location newLoc = new Location(location);
    double lat = location.getLatitude();
    double lon = location.getLongitude();

    String urlString = HOST_ADDRESS;
    urlString += "?lat=" + lat;
    urlString += "&lon=" + lon;
    URL url;
    try {
        url = new URL(urlString);
    } catch (MalformedURLException e) {
        Log.e(TAG, "Error: could not build URL");
        Log.e(TAG, e.getMessage());
        return null;
    }
    HttpsURLConnection connection = null;
    JSONObject json = null;
    InputStream is = null;
    try {
        connection = (HttpsURLConnection) url.openConnection();
        connection.setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
        is = connection.getInputStream();

    } catch (IOException e) {
        Log.e(TAG, "Error while connectiong to " + url.toString());
        Log.e(TAG, e.getMessage());
        return null;
    }
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    try {
        String line = reader.readLine();
        System.out.println("Line " + line);
        json = new JSONObject(line);
        newLoc.setLatitude(json.getDouble("lat"));
        newLoc.setLongitude(json.getDouble("lon"));
    } catch (IOException e) {
        Log.e(TAG, "Error: could not read from BufferedReader");
        Log.e(TAG, e.getMessage());
        return null;
    } catch (JSONException e) {
        Log.e(TAG, "Error: could not read from JSON");
        Log.e(TAG, e.getMessage());
        return null;
    }
    connection.disconnect();
    return newLoc;
}

From source file:com.microsoft.speech.tts.OxfordAuthentication.java

private void HttpPost(String AccessTokenUri, String requestDetails) {
    InputStream inSt = null;/*from w  ww  .  j  av  a  2s. co  m*/
    HttpsURLConnection webRequest = null;

    this.token = null;
    //Prepare OAuth request
    try {
        URL url = new URL(AccessTokenUri);
        webRequest = (HttpsURLConnection) url.openConnection();
        webRequest.setDoInput(true);
        webRequest.setDoOutput(true);
        webRequest.setConnectTimeout(5000);
        webRequest.setReadTimeout(5000);
        webRequest.setRequestProperty("content-type", "application/x-www-form-urlencoded");
        webRequest.setRequestMethod("POST");

        byte[] bytes = requestDetails.getBytes();
        webRequest.setRequestProperty("content-length", String.valueOf(bytes.length));
        webRequest.connect();

        DataOutputStream dop = new DataOutputStream(webRequest.getOutputStream());
        dop.write(bytes);
        dop.flush();
        dop.close();

        inSt = webRequest.getInputStream();
        InputStreamReader in = new InputStreamReader(inSt);
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }

        bufferedReader.close();
        in.close();
        inSt.close();
        webRequest.disconnect();

        // parse the access token from the json format
        String result = strBuffer.toString();
        JSONObject jsonRoot = new JSONObject(result);
        this.token = new OxfordAccessToken();

        if (jsonRoot.has("access_token")) {
            this.token.access_token = jsonRoot.getString("access_token");
        }

        if (jsonRoot.has("token_type")) {
            this.token.token_type = jsonRoot.getString("token_type");
        }

        if (jsonRoot.has("expires_in")) {
            this.token.expires_in = jsonRoot.getString("expires_in");
        }

        if (jsonRoot.has("scope")) {
            this.token.scope = jsonRoot.getString("scope");
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Exception error", e);
    }
}