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:Main.java

public static boolean selectServer() {
    boolean status = false;
    for (String host : host_arr) {
        String str = host + Servlet_phone;
        HttpURLConnection conn = null;
        try {//from  w w  w.ja  va2s .c om
            conn = (HttpURLConnection) new URL(str).openConnection();
            conn.setConnectTimeout(4000);
            int result = conn.getResponseCode();
            if (result == HttpURLConnection.HTTP_OK) {
                HOST = str;//
                HOST_PORT = host;
                status = true;
                break;
            } else {
            }
        } catch (MalformedURLException e) {
        } catch (IOException e) {
        } finally {
            if (conn != null) {
                conn.disconnect();
                conn = null;
            }
        }
    }
    return status;
}

From source file:com.example.admin.processingboilerplate.JsonIO.java

public static StringBuilder load(HttpURLConnection con) {
    StringBuilder sb = new StringBuilder();
    BufferedReader br = null;/*from w ww.ja  v a 2  s .  c  om*/
    try {
        br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
        String s;
        while ((s = br.readLine()) != null)
            sb.append(s).append('\n');
    } catch (IOException e) {
        Log.e("loadJson", e.getMessage(), e);
    } finally {
        try {
            if (br != null)
                br.close();
            con.disconnect();
        } catch (IOException e) {
            Log.e("loadJson", e.getMessage(), e);
        }
    }
    return sb;
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doGET(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;//from w  w w.j  a  v  a2 s . c  om
    String content = "";
    for (int i = 0; i < params.size(); i++) {
        content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "="
                + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
    }
    URL url = new URL(urlstr + "?" + content.substring(1));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.connect();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:Main.java

/**
 * This method fetches data from a given url
 *
 * @param strUrl Url from which the data will be fetched
 * @return A String representing the resource obtained in the connection
 * @throws IOException If something went wrong with the connection
 *//* w w  w .j  av  a2s. co  m*/
public static String getDataFromUrl(String strUrl) throws IOException {
    InputStream iStream;
    HttpURLConnection urlConnection;
    URL url = new URL(strUrl);

    // Creating an http connection to communicate with url
    urlConnection = (HttpURLConnection) url.openConnection();

    // Connecting to url
    urlConnection.connect();

    // Reading data from url
    iStream = urlConnection.getInputStream();

    BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

    StringBuilder sb = new StringBuilder();

    String line;
    while ((line = br.readLine()) != null) {
        sb.append(line);
    }
    br.close();
    iStream.close();
    urlConnection.disconnect();
    return sb.toString();
}

From source file:com.andrious.btc.data.jsonUtils.java

private static boolean handleResponse(int response, HttpURLConnection conn) {

    if (response == HttpURLConnection.HTTP_OK) {

        return true;
    }//from   w  w  w  .j a  v a2s . c om

    if (response == HttpURLConnection.HTTP_MOVED_TEMP || response == HttpURLConnection.HTTP_MOVED_PERM
            || response == HttpURLConnection.HTTP_SEE_OTHER) {

        String newURL = conn.getHeaderField("Location");

        conn.disconnect();

        try {

            // get redirect url from "location" header field and open a new connection again
            conn = urlConnect(newURL);

            return true;

        } catch (IOException ex) {

            throw new RuntimeException(ex);
        }
    }

    // Nothing to be done. Can't go any further.
    return false;
}

From source file:com.socialize.util.ImageUtils.java

public static Bitmap getBitmapFromURL(String src) {
    Bitmap myBitmap = null;//  w w  w.  j  a  va  2s. c  o m
    HttpURLConnection connection = null;

    try {
        URL url = new URL(src);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        myBitmap = BitmapFactory.decodeStream(input);
    } catch (IOException e) {
        e.printStackTrace();
        myBitmap = null;
    } finally {
        try {
            connection.disconnect();
        } catch (Exception ignored) {
        }
    }

    return myBitmap;
}

From source file:com.uk_postcodes.api.Postcode.java

/**
 * Get the postcode closest to the location.
 * @param location The device's location
 * @return the closest postcode/*from  w  ww . j  a va2  s.  c  o  m*/
 * @throws Exception
 */
public static String forLocation(Location location) throws Exception {
    String address = String.format(CALL, location.getLatitude(), location.getLongitude());

    Log.d("Postcode", "Calling: " + address);

    URL callUrl = new URL(address);
    HttpURLConnection callConnection = (HttpURLConnection) callUrl.openConnection();
    // The ten-second rule:
    // If there's no data in 10s (or TIMEOUT), assume the worst.
    callConnection.setReadTimeout(10000);
    // Set the request method to GET.
    callConnection.setRequestMethod("GET");
    int code = callConnection.getResponseCode();
    if (code != HttpURLConnection.HTTP_OK) {
        throw new Exception("A non-200 code was returned: " + code);
    }

    String responseStr;
    responseStr = IOUtils.toString(callConnection.getInputStream());
    callConnection.disconnect();

    JsonParser jp = new JsonParser();
    JsonElement response = jp.parse(responseStr);
    return response.getAsJsonObject().get("postcode").getAsString();
}

From source file:info.dc585.hpt.NetworkUtilities.java

/**
 * Download the avatar image from the server.
 *
 * @param avatarUrl the URL pointing to the avatar image
 * @return a byte array with the raw JPEG avatar image
 *//*  w ww .  ja va  2  s .com*/
public static Bitmap downloadBitmap(final String avatarUrl) {

    // If there is no avatar, we're done
    if (TextUtils.isEmpty(avatarUrl)) {
        return null;
    }

    try {
        //Log.v(TAG, "Downloading avatar: " + avatarUrl);
        // Request the avatar image from the server, and create a bitmap
        // object from the stream we get back.
        URL url = new URL(avatarUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        try {
            final BitmapFactory.Options options = new BitmapFactory.Options();
            final Bitmap avatar = BitmapFactory.decodeStream(connection.getInputStream(), null, options);

            return avatar;

        } finally {
            connection.disconnect();
        }
    } catch (MalformedURLException muex) {
        // A bad URL - nothing we can really do about it here...
        Log.e(TAG, "Malformed avatar URL: " + avatarUrl, muex);
    } catch (IOException ioex) {
        // If we're unable to download the avatar, it's a bummer but not the
        // end of the world. We'll try to get it next time we sync.
        Log.e(TAG, "Failed to download user avatar: " + avatarUrl, ioex);
    }
    return null;
}

From source file:com.arthurpitman.common.HttpUtils.java

/**
 * Downloads a file from a URL and saves it to the local file system.
 * @param url the URL to connect to.// w w w .j a v a2 s  .  co  m
 * @param requestProperties optional request properties, <code>null</code> if not required.
 * @param outputFile local file to write to.
 * @throws IOException
 */
public static void downloadFile(final String url, final RequestProperty[] requestProperties,
        final File outputFile) throws IOException {
    for (int i = 0;; i++) {
        HttpURLConnection connection = null;
        try {
            connection = connectGet(url, requestProperties);
            StreamUtils.readStreamIntoFile(connection.getInputStream(), outputFile, BUFFER_SIZE, true);
            return;
        } catch (IOException e) {
            if (i == CONNECTION_RETRIES) {
                throw e;
            }
        } finally {
            // always close the connection
            if (connection != null) {
                connection.disconnect();
            }
        }

        // allow recovery time
        try {
            Thread.sleep(CONNECTION_RETRY_SLEEP);
        } catch (InterruptedException e) {
        }
    }
}

From source file:com.meetingninja.csse.database.ContactDatabaseAdapter.java

public static List<Contact> deleteContact(String relationID) throws IOException {

    String _url = getBaseUri().appendPath("Relations").appendPath(relationID).build().toString();
    URL url = new URL(_url);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(IRequest.DELETE);

    addRequestHeader(conn, false);/*w w  w . jav  a  2  s.c o m*/
    int responseCode = conn.getResponseCode();
    String response = getServerResponse(conn);

    boolean result = false;
    JsonNode tree = MAPPER.readTree(response);
    if (!response.isEmpty()) {
        if (!tree.has(Keys.DELETED)) {
            result = true;
        } else {
            logError(TAG, tree);
        }
    }

    conn.disconnect();
    SessionManager session = SessionManager.getInstance();
    List<Contact> contacts = getContacts(session.getUserID());
    return contacts;
}