Example usage for java.net HttpURLConnection disconnect

List of usage examples for java.net HttpURLConnection disconnect

Introduction

In this page you can find the example usage for java.net HttpURLConnection 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.example.chengcheng.network.httpstacks.HttpUrlConnStack.java

@Override
public Response performRequest(Request<?> request) {
    HttpURLConnection urlConnection = null;
    try {/*from   w  ww  .j a  va2s  .  co m*/
        // HttpURLConnection
        urlConnection = createUrlConnection(request.getmUrl());
        // headers
        setRequestHeaders(urlConnection, request);
        // Body?
        setRequestParams(urlConnection, request);
        // https ?
        configHttps(request);
        return fetchResponse(urlConnection);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;
}

From source file:net.ftb.util.DownloadUtils.java

/**
 * @param file - the name of the file, as saved to the repo (including extension)
 * @param backupLink - the link of the location to backup to if the repo copy isn't found
 * @return - the direct static link or the backup link if the file isn't found
 *//*from  ww  w  .j  av  a  2s.c o m*/
public static String getStaticCreeperhostLinkOrBackup(String file, String backupLink) {
    String resolved = (downloadServers.containsKey(Settings.getSettings().getDownloadServer()))
            ? "http://" + downloadServers.get(Settings.getSettings().getDownloadServer())
            : Locations.masterRepo;
    resolved += "/FTB2/static/" + file;
    HttpURLConnection connection = null;
    boolean good = false;
    try {
        connection = (HttpURLConnection) new URL(resolved).openConnection();
        connection.setRequestProperty("Cache-Control", "no-transform");
        connection.setRequestMethod("HEAD");
        if (connection.getResponseCode() != 200) {
            for (String server : downloadServers.values()) {
                if (connection.getResponseCode() != 200) {
                    resolved = "http://" + server + "/FTB2/static/" + file;
                    connection = (HttpURLConnection) new URL(resolved).openConnection();
                    connection.setRequestProperty("Cache-Control", "no-transform");
                    connection.setRequestMethod("HEAD");
                } else {
                    if (connection.getResponseCode() == 200)
                        good = true;
                    break;
                }
            }
        } else if (connection.getResponseCode() == 200) {
            good = true;
        }
    } catch (IOException e) {
    }
    connection.disconnect();
    if (good)
        return resolved;
    else {
        Logger.logWarn("Using backupLink for " + file);
        return backupLink;
    }
}

From source file:org.simple.net.httpstacks.HttpUrlConnStack.java

@Override
public Response performRequest(Request<?> request) {
    HttpURLConnection urlConnection = null;
    try {//from w  ww .ja  va2 s . c o m
        // HttpURLConnection
        urlConnection = createUrlConnection(request.getUrl());
        // headers
        setRequestHeaders(urlConnection, request);
        // Body?
        setRequestParams(urlConnection, request);
        // https ?
        configHttps(request);
        return fetchResponse(urlConnection);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return null;
}

From source file:com.github.bmadecoder.Authenticator.java

public long getTimeDiff() {
    if (!this.syncing) {
        return 0;
    }//from ww w. j  av  a2  s. c  o  m
    try {
        URL url = URI.create("http://m.eu.mobileservice.blizzard.com/enrollment/time.htm").toURL();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/octet-stream");
        conn.setRequestProperty("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2");
        conn.setReadTimeout(10000);
        conn.setDoInput(true);
        conn.connect();

        byte[] servertime = new byte[8];
        InputStream connectionStream = conn.getInputStream();
        connectionStream.read(servertime, 0, 8);
        connectionStream.close();
        conn.disconnect();

        return new BigInteger(servertime).longValue() - System.currentTimeMillis();
    } catch (MalformedURLException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        return 0;
    }
}

From source file:net.chuzarski.crowdednews.utils.reddit.RedditRequest.java

/**
 * Makes the request to Reddit/*from   w  w w  .j  a v  a 2s.com*/
 * @return RedditResponse Object
 * @throws IOException
 * @throws RedditException
 */
public RedditResponse fireRequest() throws IOException, RedditException {
    //create a connection
    HttpURLConnection connection = null;
    RedditResponse response = null;
    InputStream in;

    connection = (HttpURLConnection) getRequestURL().openConnection();
    in = new BufferedInputStream(connection.getInputStream());

    //create the response object
    response = parseRedditData(IOUtils.toString(in));

    //sever the connection
    connection.disconnect();

    return response;
}

From source file:export.GarminUploader.java

private Status connectNew() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;/*  w  w  w. j a  va2s.co m*/
    s.authMethod = Uploader.AuthMethod.USER_PASS;

    FormValues fv = new FormValues();
    fv.put("service", "http://connect.garmin.com/post-auth/login");
    fv.put("clientId", "GarminConnect");
    fv.put("consumeServiceTicket", "false");

    HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv);
    addCookies(conn);
    expectResponse(conn, 200, "Connection 1: ");
    getCookies(conn);
    getFormValues(conn);
    conn.disconnect();

    // try again
    FormValues data = new FormValues();
    data.put("username", username);
    data.put("password", password);
    data.put("_eventId", "submit");
    data.put("embed", "true");
    data.put("lt", formValues.get("lt"));

    conn = post("https://sso.garmin.com/sso/login", fv);
    conn.setInstanceFollowRedirects(false);
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);
    postData(conn, data);
    expectResponse(conn, 200, "Connection 2: ");
    getCookies(conn);
    String html = getFormValues(conn);
    conn.disconnect();

    /* this is really horrible */
    int start = html.indexOf("?ticket=");
    if (start == -1) {
        throw new IOException("Invalid login, unable to locate ticket");
    }
    start += "?ticket=".length();
    int end = html.indexOf("'", start);
    String ticket = html.substring(start, end);

    // connection 3...
    fv.clear();
    fv.put("ticket", ticket);

    conn = get("http://connect.garmin.com/post-auth/login", fv);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    expectResponse(conn, 302, "Connection 3: ");
    List<String> fields = conn.getHeaderFields().get("location");
    getCookies(conn);

    // connection 4...
    conn = get(fields.get(0), null);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    expectResponse(conn, 302, "Connection 4: ");
    getCookies(conn);
    conn.disconnect();
    return checkLogin();
}

From source file:Main.java

@TargetApi(Build.VERSION_CODES.KITKAT)
public static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
    HttpURLConnection conn = null;
    BufferedReader reader = null;
    String rs = null;/*from w  w  w  .  j  av a2  s. co m*/
    try {
        StringBuffer sb = new StringBuffer();
        if (method == null || method.equals("GET")) {
            strUrl = strUrl + "?" + urlencode(params);
        }
        URL url = new URL(strUrl);
        conn = (HttpURLConnection) url.openConnection();
        if (method == null || method.equals("GET")) {
            conn.setRequestMethod("GET");
        } else {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.setRequestProperty("User-agent", userAgent);
        conn.setUseCaches(false);
        conn.setConnectTimeout(DEF_CONN_TIMEOUT);
        conn.setReadTimeout(DEF_READ_TIMEOUT);
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        if (params != null && method.equals("POST")) {
            try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                out.writeBytes(urlencode(params));
            }
        }
        InputStream is = conn.getInputStream();
        reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
        String strRead = null;
        while ((strRead = reader.readLine()) != null) {
            sb.append(strRead);
        }
        rs = sb.toString();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
    return rs;
}

From source file:org.devnexus.aerogear.HttpRestProvider.java

/**
 * {@inheritDoc}/*  w ww .ja va 2 s. c om*/
 */
@Override
public HeaderAndBody post(byte[] data) throws RuntimeException {
    HttpURLConnection urlConnection = null;

    try {
        urlConnection = prepareConnection();
        urlConnection.setRequestMethod("POST");
        addBodyRequest(urlConnection, data);
        return getHeaderAndBody(urlConnection);

    } catch (IOException e) {
        Log.e(TAG, "Error on POST of " + url, e);
        throw new RuntimeException(e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:org.devnexus.aerogear.HttpRestProvider.java

/**
 * {@inheritDoc}//w w  w . j  a v a  2  s. c o  m
 */
@Override
public HeaderAndBody put(String id, byte[] data) throws RuntimeException {
    HttpURLConnection urlConnection = null;

    try {
        urlConnection = prepareConnection(id);
        urlConnection.setRequestMethod("PUT");
        addBodyRequest(urlConnection, data);

        return getHeaderAndBody(urlConnection);
    } catch (IOException e) {
        Log.e(TAG, "Error on PUT of " + url, e);
        throw new RuntimeException(e);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}