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:dataHandlers.AccessFacebook.java

private static String responsToString(URLConnection respons) {
    String stringRespons = "";
    try {//from w  ww . j  a  v a2s.c o  m
        stringRespons = new Scanner(respons.getInputStream(), "UTF-8").useDelimiter("\\A").next();
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Resopons converstion failed", e);
    }
    return stringRespons;
}

From source file:com.android.bandwidthtest.util.BandwidthTestUtil.java

/**
 * Download a given file from a target url to a given destination file.
 * @param targetUrl the url to download// w ww  .  j a va2  s.co m
 * @param file the {@link File} location where to save to
 * @return true if it succeeded
 */
public static boolean DownloadFromUrl(String targetUrl, File file) {
    try {
        URL url = new URL(targetUrl);
        Log.d(LOG_TAG, "Download begining");
        Log.d(LOG_TAG, "Download url:" + url);
        Log.d(LOG_TAG, "Downloaded file name:" + file.getAbsolutePath());
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();
    } catch (IOException e) {
        Log.d(LOG_TAG, "Failed to download file with error: " + e);
        return false;
    }
    return true;
}

From source file:Main.java

public static File getFileFromCacheOrURL(File cacheDir, URL url) throws IOException {
    Log.i(TAG, "getFileFromCacheOrURL(): url = " + url.toExternalForm());

    String filename = url.getFile();
    int lastSlashPos = filename.lastIndexOf('/');
    String fileNameNoPath = new String(lastSlashPos == -1 ? filename : filename.substring(lastSlashPos + 1));

    File file = new File(cacheDir, fileNameNoPath);

    if (file.exists()) {
        if (file.length() > 0) {
            Log.i(TAG, "File exists in cache as: " + file.getAbsolutePath());
            return file;
        } else {/*w w w  .  j a  v  a2s .  c om*/
            Log.i(TAG, "Deleting zero length file " + file.getAbsolutePath());
            file.delete();
        }
    }

    Log.i(TAG, "File " + file.getAbsolutePath() + " does not exists.");

    URLConnection ucon = url.openConnection();
    ucon.setReadTimeout(5000);
    ucon.setConnectTimeout(30000);

    InputStream is = ucon.getInputStream();
    BufferedInputStream inStream = new BufferedInputStream(is, 1024 * 5);
    FileOutputStream outStream = new FileOutputStream(file);
    byte[] buff = new byte[5 * 1024];

    // Read bytes (and store them) until there is nothing more to read(-1)
    int len;
    while ((len = inStream.read(buff)) != -1) {
        outStream.write(buff, 0, len);
    }

    // Clean up
    outStream.flush();
    outStream.close();
    inStream.close();
    return file;
}

From source file:net.meltdowntech.steamstats.SteamGame.java

public static SteamGame fetchGame(int id) {
    //Create query url
    String url = Steam.URL + Steam.GAME_DATA + "?key=" + Steam.KEY + "&appid=" + id;
    try {/*from  ww w.  j  av a2 s  . c  o  m*/
        //Attempt connection and parse
        URL steam = new URL(url);
        URLConnection steamConn = steam.openConnection();
        Reader steamReader = new InputStreamReader(steamConn.getInputStream());
        JSONTokener steamTokener = new JSONTokener(steamReader);
        JSONObject data = (JSONObject) steamTokener.nextValue();
        JSONObject response = data.getJSONObject("game");
        SteamGame game = new SteamGame();

        //Parse each field
        Iterator keys = response.keys();
        while (keys.hasNext()) {
            String key = (String) keys.next();
            game.values.put(key, response.get(key));
        }
        return game;
    } catch (MalformedURLException ex) {
        Util.printError("Invalid URL");
    } catch (IOException | JSONException ex) {
        Util.printError("Invalid data");
    } catch (Exception ex) {
        Util.printError("Generic error");
    }
    return new SteamGame();
}

From source file:com.velonuboso.made.core.rat.RatNameHelper.java

public static String getText(URL url) throws Exception {
    URLConnection connection = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

    StringBuilder response = new StringBuilder();
    String inputLine;//from   w  w w.  j  av a 2s  .  c  o  m

    while ((inputLine = in.readLine()) != null)
        response.append(inputLine + "\n");

    in.close();

    return response.toString();
}

From source file:net.meltdowntech.steamstats.SteamGame.java

public static List<SteamGame> fetchGames(SteamUser user, boolean all) {
    List<SteamGame> games = new ArrayList<>();

    Util.printDebug("Fetching games");
    //Create query url
    String url = Steam.URL + Steam.GAME_OWNED + "?key=" + Steam.KEY + "&include_played_free_games&steamid="
            + user.getCommunityId();/* w w w  .  ja v  a  2 s .co  m*/
    try {
        //Attempt connection and parse
        URL steam = new URL(url);
        URLConnection steamConn = steam.openConnection();
        Reader steamReader = new InputStreamReader(steamConn.getInputStream());
        JSONTokener steamTokener = new JSONTokener(steamReader);
        JSONObject data = (JSONObject) steamTokener.nextValue();
        JSONObject response = data.getJSONObject("response");
        JSONArray apps = response.getJSONArray("games");

        Util.printInfo(String.format("%d game%s allotted", apps.length(), apps.length() == 1 ? "" : "s"));
        //Parse each game
        for (int y = 0; y < apps.length(); y++) {
            JSONObject app = apps.getJSONObject(y);
            SteamGame game = all ? fetchGame(app.getInt("appid")) : new SteamGame();

            //Parse each field
            Iterator keys = app.keys();
            while (keys.hasNext()) {
                String key = (String) keys.next();
                game.values.put(key, app.get(key));
            }
            games.add(game);
        }

    } catch (MalformedURLException ex) {
        Util.printError("Invalid URL");
    } catch (IOException | JSONException ex) {
        Util.printError("Invalid data");
    } catch (Exception ex) {
        Util.printError("Generic error");
    }
    Util.printDebug("Done fetching games");
    return games;
}

From source file:emily.command.fun.CatFactCommand.java

public static String getCatFact() {
    try {/*ww  w .  jav  a 2  s . co  m*/
        URL loginurl = new URL("https://catfact.ninja/fact");
        URLConnection yc = loginurl.openConnection();
        yc.setConnectTimeout(10 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        String inputLine = in.readLine();
        JsonParser parser = new JsonParser();
        JsonObject array = parser.parse(inputLine).getAsJsonObject();
        return ":cat:  " + array.get("fact").getAsString();
    } catch (Exception e) {
        System.out.println(e);
    }
    return null;
}

From source file:eu.scape_project.pit.util.FileUtils.java

/**
 * Read file of URL into file.//from   ww w  . ja va  2s  .c o  m
 * @param url URL where the input file is located
 * @param ext 
 * @return Result file
 * @throws IOException 
 */
public static File urlToFile(URL url, String ext) throws IOException {
    File fOut = null;

    fOut = getTmpFile("fromurl", "." + ext);

    URLConnection uc = url.openConnection();
    logger.info("ContentType: " + uc.getContentType());
    InputStream in = uc.getInputStream();
    org.apache.commons.io.FileUtils.copyInputStreamToFile(in, fOut);
    logger.info("File of length " + fOut.length() + " created from URL " + url.toString());

    in.close();

    return fOut;
}

From source file:it.isti.cnr.hpc.europeana.hackthon.domain.FreebaseMapper.java

public static Freebase getInstanceFromQuery(String query)
        throws IOException, EntityException, NoResultException {
    KeyGenerator kg = new KeyGenerator();
    Integer key = kg.getKey(query);
    if (cache.containsKey(key))
        return cache.get(key);

    String uri = SuggestionProperties.getInstance().getProperty("freebase.query.api");
    uri += query;//ww w  .j  a  va2s . co m

    try {
        uri = URIUtil.encodeQuery(uri);
    } catch (URIException e) {
        logger.error("Error producing the enconded query for {}", uri);
        return null;
    }
    try {
        URL u = new URL(uri);
        URLConnection uc = u.openConnection();

        InputStream is = uc.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        Freebase fb = parseFromJson(br);
        cache.put(key, fb);
        return fb;

    } catch (IOException e) {
        throw new IOException("error retrieving the query from freebase");

    }

}

From source file:mc.lib.network.NetworkHelper.java

public static Bitmap getBitmap(String url) {
    Bitmap res = null;/*  w ww  .j  ava 2 s  .  com*/
    InputStream is = null;
    try {
        URLConnection c = new URL(url).openConnection();
        c.connect();
        is = c.getInputStream();
        res = BitmapFactory.decodeStream(is);
    } catch (MalformedURLException e) {
        Log.e(LOGTAG, "Wrong url format", e);
    } catch (Exception e) {
        Log.e(LOGTAG, "Cannot get bitmap", e);
    } finally {
        StreamHelper.close(is);
    }
    return res;
}