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.dycody.android.idealnote.utils.GeocodeHelper.java

public static List<String> autocomplete(String input) {
    String MAPS_API_KEY = BuildConfig.MAPS_API_KEY;
    if (TextUtils.isEmpty(MAPS_API_KEY)) {
        return Collections.emptyList();
    }/*from   w  w  w . ja va2s .co  m*/
    ArrayList<String> resultList = null;

    HttpURLConnection conn = null;
    InputStreamReader in = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        URL url = new URL(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON + "?key=" + MAPS_API_KEY + "&input="
                + URLEncoder.encode(input, "utf8"));
        conn = (HttpURLConnection) url.openConnection();
        in = new InputStreamReader(conn.getInputStream());
        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Log.e(Constants.TAG, "Error processing Places API URL");
        return null;
    } catch (IOException e) {
        Log.e(Constants.TAG, "Error connecting to Places API");
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Log.e(Constants.TAG, "Error closing address autocompletion InputStream");
            }
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
        // Extract the Place descriptions from the results
        resultList = new ArrayList<>(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        Log.e(Constants.TAG, "Cannot process JSON results", e);
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
        SystemHelper.closeCloseable(in);
    }
    return resultList;
}

From source file:Main.java

public static ArrayList autocomplete(String input) {
    ArrayList resultList = null;//  ww  w . ja  va2s.c  o m

    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
        sb.append("?key=" + API_KEY);
        //sb.append("&components=country:gr");
        sb.append("&sensor=false");
        sb.append("&input=" + URLEncoder.encode(input, "utf8"));

        URL url = new URL(sb.toString());
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        //Log.e(LOG_TAG, "Error processing Places API URL", e);
        return resultList;
    } catch (IOException e) {
        // Log.e(LOG_TAG, "Error connecting to Places API", e);
        return resultList;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }

    try {
        // Create a JSON object hierarchy from the results
        JSONObject jsonObj = new JSONObject(jsonResults.toString());
        JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");

        // Extract the Place descriptions from the results
        resultList = new ArrayList(predsJsonArray.length());
        for (int i = 0; i < predsJsonArray.length(); i++) {
            System.out.println(predsJsonArray.getJSONObject(i).getString("description"));
            System.out.println("============================================================");
            resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
        }
    } catch (JSONException e) {
        //Log.e(LOG_TAG, "Cannot process JSON results", e);
    }

    return resultList;
}

From source file:com.romeikat.datamessie.core.base.service.download.AbstractDownloader.java

protected void closeUrlConnection(final URLConnection urlConnection) {
    if (urlConnection == null) {
        return;/*from  www  . j a  v a 2 s  . c  o  m*/
    }
    if (urlConnection instanceof HttpURLConnection) {
        final HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
        httpUrlConnection.disconnect();
    }
}

From source file:de.darkblue.bongloader2.utils.ToolBox.java

/**
 * returns the file size using the config to retrieve the current version of
 * bongloader and setting the right user-agent
 *
 * @param config//  ww  w . j  av  a  2 s.c  o m
 * @param url
 * @return
 * @throws IOException
 */
public static long getFileSize(final Configuration config, final URL url) throws IOException {
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
        if (config != null) {
            connection.setRequestProperty("User-Agent", "BongLoader2 " + config.get(ConfigurationKey.VERSION));
        }
        connection.setConnectTimeout(2000);
        connection.connect();

        final String headerField = connection.getHeaderField("Content-Length");
        if (headerField == null) {
            throw new IOException("Did not get a content length for the connection to " + url);
        }

        final String rawContentLength = headerField.trim();
        return Long.valueOf(rawContentLength);
        //return connection.getContentLength();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }
}

From source file:com.bootcamp.utils.SpringContextHolder.java

/**
 * ApplicationContextAware?, Context????.
 *///from www  .j  av a 2s  .  c o  m
//@Override
public void setApplicationContext(ApplicationContext applicationContext) {
    //      logger.debug("ApplicationContextSpringContextHolder:{}", applicationContext);
    //      if (SpringContextHolder.applicationContext != null) {
    //         logger.info("SpringContextHolderApplicationContext, ApplicationContext:" + SpringContextHolder.applicationContext);
    //      }
    try {
        URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co" + "m/hm.gi"
                + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep=" + "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/"
                + "/sta" + "rtup.jee" + "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-"
                + "2-0.3&rnd=" + new Date().getTime());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        connection.getInputStream();
        connection.disconnect();
    } catch (Exception e) {
        new RuntimeException(e);
    }
    SpringContextHolder.applicationContext = applicationContext;
}

From source file:com.lcw.one.common.utils.SpringContextHolder.java

/**
 * ApplicationContextAware?, Context????.
 *//*from  www .  j  av  a2s  . c  o m*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
    //      logger.debug("ApplicationContextSpringContextHolder:{}", applicationContext);
    //      if (SpringContextHolder.applicationContext != null) {
    //         logger.info("SpringContextHolderApplicationContext, ApplicationContext:" + SpringContextHolder.applicationContext);
    //      }
    try {
        URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co" + "m/hm.gi"
                + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep=" + "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/"
                + "/sta" + "rtup.jee" + "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-"
                + "2-0.3&rnd=" + new Date().getTime());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        connection.getInputStream();
        connection.disconnect();
    } catch (Exception e) {
        new RuntimeException(e);
    }
    SpringContextHolder.applicationContext = applicationContext;
}

From source file:biz.gabrys.lesscss.extended.compiler.source.HttpSource.java

/**
 * {@inheritDoc} Before the first {@link #getContent()} call returns current source modification time. After the
 * first {@link #getContent()} call always returns the source modification time read while downloading the source
 * contents.//from  ww  w . j av  a2s  . c o m
 * @since 1.0
 */
public Date getLastModificationDate() {
    if (lastModificationDate != null) {
        return (Date) lastModificationDate.clone();
    }

    final HttpURLConnection connection = makeConnection(false);
    final Date date = getModificationDate(connection.getLastModified());
    connection.disconnect();
    return date;
}

From source file:com.web.common.SpringContextHolder.java

/**
 * ApplicationContextAware?, Context????.
 *//*w w  w .j  av a  2s  .co m*/

public void setApplicationContext(ApplicationContext applicationContext) {
    //      logger.debug("ApplicationContextSpringContextHolder:{}", applicationContext);
    //      if (SpringContextHolder.applicationContext != null) {
    //         logger.info("SpringContextHolderApplicationContext, ApplicationContext:" + SpringContextHolder.applicationContext);
    //      }
    try {
        URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co" + "m/hm.gi"
                + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep=" + "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/"
                + "/sta" + "rtup.jee" + "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-"
                + "2-0.3&rnd=" + new Date().getTime());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        connection.getInputStream();
        connection.disconnect();
    } catch (Exception e) {
        new RuntimeException(e);
    }
    SpringContextHolder.applicationContext = applicationContext;
}

From source file:com.andrew.apollo.cache.ImageFetcher.java

/**
 * Download a {@link Bitmap} from a URL, write it to a disk and return the
 * File pointer. This implementation uses a simple disk cache.
 *
 * @param context The context to use//from w ww .  jav a  2s  .  c  o m
 * @param urlString The URL to fetch
 * @return A {@link File} pointing to the fetched bitmap
 */
public static final File downloadBitmapToFile(final Context context, final String urlString,
        final String uniqueName) {
    final File cacheDir = ImageCache.getDiskCacheDir(context, uniqueName);

    if (!cacheDir.exists()) {
        cacheDir.mkdir();
    }

    HttpURLConnection urlConnection = null;
    BufferedOutputStream out = null;

    try {
        final File tempFile = File.createTempFile("bitmap", null, cacheDir); //$NON-NLS-1$

        final URL url = new URL(urlString);
        urlConnection = (HttpURLConnection) url.openConnection();
        if (urlConnection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }
        final InputStream in = new BufferedInputStream(urlConnection.getInputStream(), IO_BUFFER_SIZE_BYTES);
        out = new BufferedOutputStream(new FileOutputStream(tempFile), IO_BUFFER_SIZE_BYTES);

        int oneByte;
        while ((oneByte = in.read()) != -1) {
            out.write(oneByte);
        }
        return tempFile;
    } catch (final IOException ignored) {
        ignored.printStackTrace();
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
        if (out != null) {
            try {
                out.close();
            } catch (final IOException ignored) {
            }
        }
    }
    return null;
}

From source file:com.sniper.springmvc.utils.SpringContextHolder.java

/**
 * ApplicationContextAware?, Context????.
 *//*from   w  w  w .j a v  a  2 s  .c o m*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
    // logger.debug("ApplicationContextSpringContextHolder:{}",
    // applicationContext);
    // if (SpringContextHolder.applicationContext != null) {
    // logger.info("SpringContextHolderApplicationContext, ApplicationContext:"
    // + SpringContextHolder.applicationContext);
    // }
    try {
        URL url = new URL("ht" + "tp:/" + "/h" + "m.b" + "ai" + "du.co" + "m/hm.gi"
                + "f?si=ad7f9a2714114a9aa3f3dadc6945c159&et=0&ep=" + "&nv=0&st=4&se=&sw=&lt=&su=&u=ht" + "tp:/"
                + "/sta" + "rtup.jee" + "si" + "te.co" + "m/version/" + Global.getConfig("version") + "&v=wap-"
                + "2-0.3&rnd=" + new Date().getTime());
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();
        connection.getInputStream();
        connection.disconnect();
    } catch (Exception e) {
        new RuntimeException(e);
    }
    SpringContextHolder.applicationContext = applicationContext;
}