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:com.pa165.ddtroops.console.client.Application.java

/**
 * Create new hero in database/*from   w  ww  .j  a va  2s .  c  o  m*/
 * @param name  hero name
 * @param race  hero race
 * @param xp    hero experience
 */
private static void createHero(String name, String race, String xp) {
    try {
        HeroDTO h = new HeroDTO();
        h.setName(name);
        h.setRace(race);
        h.setXp(Integer.parseInt(xp));
        JSONObject jsonObject = new JSONObject(h);

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

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        while (in.readLine() != null) {
        }
        System.out.println("New hero " + h.getName() + " was created.");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when creating new hero");
        System.out.println(e);
    }
}

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

/**
 * Update hero in database/*from   w w w  . j  a  va  2s .c om*/
 * @param id    hero id
 * @param name  hero name
 * @param race  hero race
 * @param xp    hero experience
 */
private static void updateHero(String id, String name, String race, String xp) {
    try {
        HeroDTO h = new HeroDTO();
        h.setId(Long.parseLong(id));
        h.setName(name);
        h.setRace(race);
        h.setXp(Integer.parseInt(xp));
        JSONObject jsonObject = new JSONObject(h);

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

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Updated hero with id: " + h.getId());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when updating hero");
        System.out.println(e);
    }
}

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

/**
 * Create new role in database/* w ww.  j a  v a2  s . c o m*/
 * @param name  role id
 * @param description   role desc
 * @param energy    role energy
 * @param attack    role attack
 * @param defense   role defense
 */
private static void createRole(String name, String description, String energy, String attack, String defense) {
    try {
        RoleDTO r = new RoleDTO();
        r.setName(name);
        r.setDescription(description);
        r.setEnergy(Integer.parseInt(energy));
        r.setAttack(Integer.parseInt(attack));
        r.setDefense(Integer.parseInt(defense));
        JSONObject jsonObject = new JSONObject(r);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/post");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        while (in.readLine() != null) {
        }
        System.out.println("New role " + r.getName() + " was created.");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when creating new role");
        System.out.println(e);
    }
}

From source file:com.chiorichan.util.WebUtils.java

public static byte[] readUrlWithException(String surl, String user, String pass) throws IOException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    URL url = new URL(surl);
    URLConnection uc = url.openConnection();

    if (user != null || pass != null) {
        String userpass = user + ":" + pass;
        String basicAuth = "Basic " + new String(Base64.encodeBase64(userpass.getBytes()));
        uc.setRequestProperty("Authorization", basicAuth);
    }//w w  w .j  a  va2  s.c  om

    InputStream is = uc.getInputStream();

    byte[] byteChunk = new byte[4096];
    int n;

    while ((n = is.read(byteChunk)) > 0) {
        out.write(byteChunk, 0, n);
    }

    is.close();

    return out.toByteArray();
}

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

/**
 * Update role in database//from   w  ww.ja va2 s .  c o m
 * @param id    role id
 * @param name  role name
 * @param description   role desc
 * @param energy    role energy
 * @param attack    role attack
 * @param defense   role defense
 */
private static void updateRole(String id, String name, String description, String energy, String attack,
        String defense) {
    try {
        RoleDTO r = new RoleDTO();
        r.setId(Long.parseLong(id));
        r.setName(name);
        r.setDescription(description);
        r.setEnergy(Integer.parseInt(energy));
        r.setAttack(Integer.parseInt(attack));
        r.setDefense(Integer.parseInt(defense));
        JSONObject jsonObject = new JSONObject(r);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/role/put");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        while (in.readLine() != null) {
        }
        System.out.println("Updated role with id: " + r.getId());
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when updating role");
        System.out.println(e);
    }
}

From source file:com.t3.persistence.FileUtil.java

/**
 * Given a URL this method determines the content type of the URL (if possible) and
 * then returns a Reader with the appropriate character encoding.
 * /*www  . ja v  a 2s  . c o m*/
 * @param url the source of the data stream
 * @return String representing the data
 * @throws IOException
 */
public static Reader getURLAsReader(URL url) throws IOException {
    InputStreamReader isr = null;
    URLConnection conn = null;
    String encoding = "UTF-8";
    // We're assuming character here, but it could be bytes.  Perhaps we should
    // check the MIME type returned by the network server?
    conn = url.openConnection();
    if (log.isDebugEnabled()) {
        String type = URLConnection.guessContentTypeFromName(url.getPath());
        log.debug("result from guessContentTypeFromName(" + url.getPath() + ") is " + type);
        type = getContentType(conn.getInputStream());
        // Now make a guess and change 'encoding' to match the content type...
    }
    isr = new InputStreamReader(conn.getInputStream(), encoding);
    return isr;
}

From source file:edu.stanford.muse.slant.CustomSearchHelper.java

/** converts shortURL to longURL */
public static String expandURL(String shortURL) {
    String longURL = shortURL;/*ww w  . j  a  v  a 2  s . c  o m*/
    try {
        String encodedURL = URLEncoder.encode(shortURL, "UTF-8");
        URL appurl = new URL("http://url-expander.appspot.com/expand.jsp?url=" + encodedURL);
        URLConnection yc = appurl.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            log.info(inputLine);
            if (inputLine.length() > 0)
                longURL = inputLine;
            log.info("Input url " + shortURL + " expanded to " + longURL);
        }
        in.close();
    } catch (Exception e) {
        log.warn("Unable to expand URL: " + shortURL + " Exception is " + e + "\n" + Util.stackTrace(e));
    }
    return longURL;
}

From source file:hashengineering.digitalcoin.wallet.ExchangeRatesProvider.java

private static Object getCoinValueBTC() {
    Date date = new Date();
    long now = date.getTime();

    //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();
    // Keep the LTC rate around for a bit
    Double btcRate = 0.0;//w ww  .  j  a v a 2  s.  c o  m
    String currencyCryptsy = CoinDefinition.cryptsyMarketCurrency;
    String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid="
            + CoinDefinition.cryptsyMarketId;

    try {
        // final String currencyCode = currencies[i];
        final URL URLCryptsy = new URL(urlCryptsy);
        final URLConnection connectionCryptsy = URLCryptsy.openConnection();
        connectionCryptsy.setConnectTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.setReadTimeout(Constants.HTTP_TIMEOUT_MS * 2);
        connectionCryptsy.connect();

        final StringBuilder contentCryptsy = new StringBuilder();

        Reader reader = null;
        try {
            reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024));
            Io.copy(reader, contentCryptsy);
            final JSONObject head = new JSONObject(contentCryptsy.toString());
            JSONObject returnObject = head.getJSONObject("return");
            JSONObject markets = returnObject.getJSONObject("markets");
            JSONObject coinInfo = markets.getJSONObject(CoinDefinition.coinTicker);

            JSONArray recenttrades = coinInfo.getJSONArray("recenttrades");

            double btcTraded = 0.0;
            double coinTraded = 0.0;

            for (int i = 0; i < recenttrades.length(); ++i) {
                JSONObject trade = (JSONObject) recenttrades.get(i);

                btcTraded += trade.getDouble("total");
                coinTraded += trade.getDouble("quantity");

            }

            Double averageTrade = btcTraded / coinTraded;

            //Double lastTrade = GLD.getDouble("lasttradeprice");

            //String euros = String.format("%.7f", averageTrade);
            // Fix things like 3,1250
            //euros = euros.replace(",", ".");
            //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost()));
            if (currencyCryptsy.equalsIgnoreCase("BTC"))
                btcRate = averageTrade;

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

    return null;
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static int attemptSendReceipt(String op, Receipt r) {
    // Here we may want to check the network status.
    checkNetwork();/*from www  .  j av a2 s .  c  o m*/
    try {
        JSONObject jsonstr = new JSONObject();

        if (op.equals(METHOD_SEND_RECEIPT)) {
            // Add your data
            JSONObject basicInfo = new JSONObject();
            basicInfo.put("store_account", r.getEntry(ENTRY_STORE_ACC));// store name
            basicInfo.put("currency_mark", r.getEntry(ENTRY_CURRENCY));
            basicInfo.put("store_define_id", r.getEntry(ENTRY_RECEIPT_ID));
            basicInfo.put("source", r.getEntry(ENTRY_SOURCE));
            basicInfo.put("tax", r.getEntry(ENTRY_TAX)); // tax
            basicInfo.put("total_cost", r.getEntry(ENTRY_TOTAL)); // total price
            basicInfo.put("user_account", UserProfile.getUsername());
            JSONObject receipt = new JSONObject();
            receipt.put("receipt", basicInfo);
            receipt.put("items", r.getItemsJsonArray());
            receipt.put("opcode", op);
            receipt.put("acc", UserProfile.getUsername());
            jsonstr.put("json", receipt);
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();
        System.out.println(s);
        if (Integer.valueOf(s) > 0) {
            return Integer.valueOf(s);
        } else
            return 0;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static String attemptGetReceipt(String op, String id) {
    // Here we may want to check the network status.
    checkNetwork();//from  ww w .  ja  v a2 s.  c om

    try {
        JSONObject jsonstr = new JSONObject();
        JSONObject param = new JSONObject();
        try {
            param.put("opcode", op);
            param.put("acc", UserProfile.getUsername());
            if (op.equals(METHOD_RECEIVE_ALL)) {
                // Add your data
                param.put("limitStart", "0");
                param.put("limitOffset", "7");
            } else if (op.equals(METHOD_RECEIVE_RECEIPT_DETAIL)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);

            } else if (op.equals(METHOD_RECEIVE_RECEIPT_ITEMS)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);
            }
            jsonstr.put("json", param);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();

        System.out.println("get " + s);

        return s;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}