Example usage for java.net URLConnection connect

List of usage examples for java.net URLConnection connect

Introduction

In this page you can find the example usage for java.net URLConnection connect.

Prototype

public abstract void connect() throws IOException;

Source Link

Document

Opens a communications link to the resource referenced by this URL, if such a connection has not already been established.

Usage

From source file:piuk.blockchain.android.ExchangeRatesProvider.java

private static Map<String, Double> getExchangeRates() {
    try {//from   w  ww . j a  v a 2s .  co  m
        final URLConnection connection = new URL("http://bitcoincharts.com/t/weighted_prices.json")
                .openConnection();
        // https://mtgox.com/code/data/ticker.php
        // https://bitmarket.eu/api/ticker
        // http://bitcoincharts.com/t/weighted_prices.json

        connection.connect();
        final Reader is = new InputStreamReader(new BufferedInputStream(connection.getInputStream()));
        final StringBuilder content = new StringBuilder();
        IOUtils.copy(is, content);
        is.close();

        final Map<String, Double> rates = new TreeMap<String, Double>();

        final JSONObject head = new JSONObject(content.toString());
        for (@SuppressWarnings("unchecked")
        final Iterator<String> i = head.keys(); i.hasNext();) {
            final String currencyCode = i.next();
            if (!"timestamp".equals(currencyCode)) {
                final JSONObject o = head.getJSONObject(currencyCode);
                double rate = o.optDouble("24h", 0);
                if (rate == 0)
                    rate = o.optDouble("7d", 0);
                if (rate == 0)
                    rate = o.optDouble("30d", 0);

                if (rate != 0)
                    rates.put(currencyCode, rate);
            }
        }

        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.miqtech.master.client.ui.PersonalHomePhotoActivity.java

public static Bitmap getBitMBitmap(String urlpath) {
    Bitmap map = null;/*from  w  w w . j  a v a2 s.  com*/
    try {
        URL url = new URL(urlpath);
        URLConnection conn = url.openConnection();
        conn.connect();
        InputStream in;
        in = conn.getInputStream();
        map = BitmapFactory.decodeStream(in);
        // TODO Auto-generated catch block
    } catch (IOException e) {
        e.printStackTrace();
    }
    return map;
}

From source file:de.schildbach.wallet.litecoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getLycancoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    try {/*from w w w  .  j  a  v  a  2  s  .c o m*/
        String currencies[] = { "USD", "EUR" };
        String urls[] = { "https://btc-e.com/api/2/btc_usd/ticker", "https://btc-e.com/api/2/btc_eur/ticker" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                JSONObject ticker = head.getJSONObject("ticker");
                Double avg = ticker.getDouble("avg") * LycBtcRate;
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros),
                        "cryptsy.com and " + URL.getHost()));
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:model.Modele.java

/**
 * Methode qui vrifie s'il y a une connexin internet
 *
 * @return vrai s'il y a une connexion, faux s'il y a pas de connexion
 *///from   w  w w  .j  av  a  2  s  . co  m
public static boolean netIsAvailable() {
    try {
        final URL url = new URL("http://www.google.com");
        final URLConnection conn = url.openConnection();
        conn.connect();
        return true;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        return false;
    }
}

From source file:AnimatedMetadataGraph.java

public static JSONObject getAllResources(URL sfsUrl) {
    if (sfsUrl != null) {
        try {//from   w  w w  .ja  va2  s. c o m
            URL sfsGetRsrcsUrl = new URL(sfsUrl.toString() + "/admin/listrsrcs/");
            URLConnection smapConn = sfsGetRsrcsUrl.openConnection();
            smapConn.setConnectTimeout(5000);
            smapConn.connect();

            //GET reply
            BufferedReader reader = new BufferedReader(new InputStreamReader(smapConn.getInputStream()));
            StringBuffer lineBuffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null)
                lineBuffer.append(line);
            line = lineBuffer.toString();
            reader.close();

            return (JSONObject) JSONSerializer.toJSON(line);
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
            return null;
        }
    }
    return null;
}

From source file:AnimatedMetadataGraph.java

public static JSONArray getChildren(URL sfsUrl, String path) {
    if (sfsUrl != null) {
        try {//w  ww.  j ava2s.c  o  m
            URL sfsGetRsrcsUrl = new URL(sfsUrl.toString() + path);
            URLConnection smapConn = sfsGetRsrcsUrl.openConnection();
            smapConn.setConnectTimeout(5000);
            smapConn.connect();

            //GET reply
            BufferedReader reader = new BufferedReader(new InputStreamReader(smapConn.getInputStream()));
            StringBuffer lineBuffer = new StringBuffer();
            String line = null;
            while ((line = reader.readLine()) != null)
                lineBuffer.append(line);
            line = lineBuffer.toString();
            reader.close();

            JSONObject resp = (JSONObject) JSONSerializer.toJSON(line);
            return resp.optJSONArray("children");
        } catch (Exception e) {
            logger.log(Level.WARNING, "", e);
            return null;
        }
    }
    return null;
}

From source file:de.schildbach.wallet.elysium.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getElysiumCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;//from  www  . j av  a 2s  .c  om
    try {
        String currencies[] = { "USD", "BTC", "RUR" };
        String urls[] = { "https://btc-e.com/api/2/14/ticker", "https://btc-e.com/api/2/10/ticker",
                "https://btc-e.com/api/2/elsm_rur/ticker" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                JSONObject ticker = head.getJSONObject("ticker");
                Double avg = ticker.getDouble("avg");
                String euros = String.format("%.4f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode,
                        new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
                if (currencyCode.equalsIgnoreCase("BTC"))
                    btcRate = avg;
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        // Handle ELSM/EUR special since we have to do maths
        final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is elysiums priced in euros.  We want ELSM!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:de.schildbach.wallet.marscoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getmarscoinCharts() {
    final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the BTC rate around for a bit
    Double btcRate = 0.0;//  w w w .  j a v  a  2 s  . co m
    try {
        String currencies[] = { "BTC" };
        //String urls[] = {"https://cryptorush.in/api.php?get=market&m=mrs&b=btc&json=true"};
        String urls[] = { "http://hlds.ws/marscoinj/api" };
        for (int i = 0; i < currencies.length; ++i) {
            final String currencyCode = currencies[i];
            final URL URL = new URL(urls[i]);
            final URLConnection connection = URL.openConnection();
            connection.setConnectTimeout(TIMEOUT_MS);
            connection.setReadTimeout(TIMEOUT_MS);
            connection.connect();
            final StringBuilder content = new StringBuilder();

            Reader reader = null;
            try {
                reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
                IOUtils.copy(reader, content);
                final JSONObject head = new JSONObject(content.toString());
                //JSONObject ticker = head.getJSONObject("ticker");
                //rate = Float.parseFloat(head.getString("current_ask"));
                Double avg = head.getDouble("current_ask");
                //Double avg = Float.parseFloat(head.getString("current_ask"));
                String euros = String.format("%.8f", avg);
                // Fix things like 3,1250
                euros = euros.replace(",", ".");
                rates.put(currencyCode,
                        new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost()));
                if (currencyCode.equalsIgnoreCase("BTC"))
                    btcRate = avg;
            } finally {
                if (reader != null)
                    reader.close();
            }
        }
        // Handle LTC/EUR special since we have to do maths
        final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);
            final JSONObject head = new JSONObject(content.toString());
            JSONObject ticker = head.getJSONObject("ticker");
            Double avg = ticker.getDouble("avg");
            // This is bitcoins priced in euros.  We want MRS!
            avg *= btcRate;
            String s_avg = String.format("%.4f", avg).replace(',', '.');
            rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost()));
        } finally {
            if (reader != null)
                reader.close();
        }
        return rates;
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/* w  w w  .j av a 2 s.com*/
        final URL URL = new URL("https://blockchain.info/ticker");
        final URLConnection connection = URL.openConnection();
        connection.setConnectTimeout(TIMEOUT_MS);
        connection.setReadTimeout(TIMEOUT_MS);
        connection.connect();
        final StringBuilder content = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024));
            IOUtils.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                final JSONObject o = head.getJSONObject(currencyCode);
                final String rate = o.optString("15m", null);

                if (rate != null)
                    rates.put(currencyCode,
                            new ExchangeRate(currencyCode, Utils.toNanoCoins(rate), URL.getHost()));
            }

            return rates;
        } finally {
            if (reader != null)
                reader.close();
        }
    } catch (final IOException x) {
        x.printStackTrace();
    } catch (final JSONException x) {
        x.printStackTrace();
    }

    return null;
}

From source file:org.springframework.ide.eclipse.boot.core.initializr.InitializrServiceSpec.java

public static InitializrServiceSpec parseFrom(URLConnectionFactory urlConnectionFactory, URL url)
        throws IOException, Exception {
    URLConnection conn = null;
    InputStream input = null;/*  w  w  w . j a va  2s  .  c om*/
    try {
        conn = urlConnectionFactory.createConnection(url);
        conn.addRequestProperty("Accept", JSON_CONTENT_TYPE_HEADER);
        conn.connect();
        input = conn.getInputStream();
        return parseFrom(input);
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
}