Example usage for java.net URLConnection getInputStream

List of usage examples for java.net URLConnection getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

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 {/*  ww  w .j  av  a2s.  com*/
        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:com.example.cmput301.model.WebService.java

/**
 * Sets up http connection to the web server and returns the connection.
 * @param conn URLConnection/*from  www . jav  a 2 s  . c om*/
 * @param data string to send to web service.
 * @return String response from web service.
 * @throws IOException
 */
private static String getHttpResponse(URLConnection conn, String data) throws IOException {
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();
    wr.close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, httpResponse = "";
    while ((line = rd.readLine()) != null) {
        // Process line...
        httpResponse += line;
    }
    rd.close();
    return httpResponse;
}

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

private static Map<String, ExchangeRate> getBlockchainInfo() {
    try {/*from   ww w  . j  a v a  2  s.c  o  m*/
        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:com.pa165.ddtroops.console.client.Application.java

/**
 * Delete hero from database/*from   www.j a  va  2s. c  o m*/
 * @param number    hero id 
 */
private static void deleteHero(String number) {
    try {
        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/delete/" + number);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Hero with id: " + number + " was deleted");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when deleting hero");
        System.out.println(e);
    }
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Delete role from database//from w  w  w. j  a  v a 2  s. co m
 * @param number    role id
 */
private static void deleteRole(String number) {
    try {
        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/delete/" + number);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Role with id: " + number + " was deleted");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when deleting role");
        System.out.println(e);
    }
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Get specific hero with unique id/*from w  ww . j a v  a 2  s  .  co m*/
 * 
 * @param number hero id 
 */
private static void getHero(String number) {
    try {
        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/" + number);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String s = "";
        HeroDTO hero = new HeroDTO();
        while ((s = in.readLine()) != null) {
            hero = mapper.readValue(s, new TypeReference<HeroDTO>() {
            });
        }
        System.out.println("Returned hero");
        System.out.println("ID: " + hero.getId() + ", NAME: " + hero.getName() + ", RACE: " + hero.getRace()
                + ", XP: " + hero.getXp());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when returning hero");
        System.out.println(e);
    }
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Get specific role with unique id//from w  ww .j a  v a2 s.  c  o m
 * @param number role id
 */
private static void getRole(String number) {
    try {
        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/" + number);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String s = "";
        RoleDTO role = new RoleDTO();
        while ((s = in.readLine()) != null) {
            role = mapper.readValue(s, new TypeReference<RoleDTO>() {
            });
        }
        System.out.println("Returned role");
        System.out.println("ID: " + role.getId() + ", NAME: " + role.getName() + ", DESCRIPTION: "
                + role.getDescription() + ", ENERGY: " + role.getEnergy() + ", ATTACK: " + role.getAttack()
                + ", DEFENSE: " + role.getDefense());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when returning role");
        System.out.println(e);
    }
}

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 w ww .  ja v  a 2 s.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:com.itcs.commons.email.EmailAutoconfigClient.java

private static String getURLContent(String p_sURL) throws MalformedURLException, IOException {
    URL oURL;/*w  ww. j  a  va  2  s  .c o m*/
    URLConnection oConnection;
    BufferedReader oReader;
    String sLine;
    StringBuilder sbResponse;
    String sResponse = null;

    oURL = new URL(p_sURL);
    oConnection = oURL.openConnection();
    oReader = new BufferedReader(new InputStreamReader(oConnection.getInputStream()));
    sbResponse = new StringBuilder();

    while ((sLine = oReader.readLine()) != null) {
        sbResponse.append(sLine);
    }

    sResponse = sbResponse.toString();

    return sResponse;
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Pring all heroes to console window//from   ww  w .  j  a va 2s. c  o  m
 */
private static void getAllHeroes() {
    try {

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String s = "";
        List<HeroDTO> hero = new ArrayList<HeroDTO>();
        while ((s = in.readLine()) != null) {
            hero = mapper.readValue(s, new TypeReference<List<HeroDTO>>() {
            });
        }
        System.out.println("All heroes");
        for (HeroDTO h : hero) {
            System.out.println("ID: " + h.getId() + ", NAME: " + h.getName() + ", RACE: " + h.getRace()
                    + ", XP: " + h.getXp());
        }
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when returning all heroes");
        System.out.println(e);
    }
}