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.comcast.cdn.traffic_control.traffic_monitor.util.Fetcher.java

public static File downloadTM(final String url, final String authUrl, final String username,
        final String password, final int timeout) throws IOException {
    InputStream in = null;/*from  w  ww .  java 2  s  .c o m*/
    OutputStream out = null;

    try {
        final URL u = new URL(url);
        final URLConnection urlc = u.openConnection();

        if (timeout != 0) {
            urlc.setConnectTimeout(timeout);
            urlc.setReadTimeout(timeout);
        }

        if (urlc instanceof HttpsURLConnection) {
            final String cookie = getTmCookie(authUrl, username, password, timeout).toString();

            final HttpsURLConnection http = (HttpsURLConnection) urlc;
            http.setInstanceFollowRedirects(false);
            http.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(final String arg0, final SSLSession arg1) {
                    return true;
                }
            });
            http.setRequestMethod(GET_STR);
            http.setAllowUserInteraction(true);
            http.addRequestProperty("Cookie", cookie);
        }

        in = urlc.getInputStream();

        final File outputFile = File.createTempFile(tmpPrefix, tmpSuffix);
        out = new FileOutputStream(outputFile);

        IOUtils.copy(in, out);
        return outputFile;
    } finally {
        IOUtils.closeQuietly(in);
        IOUtils.closeQuietly(out);
    }
}

From source file:me.mast3rplan.phantombot.twitch.TwitchAPI.java

public JSONObject getObject(String url) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    connection.setUseCaches(false);/*ww  w  . jav a  2s .co m*/
    connection.setDefaultUseCaches(false);
    String content = IOUtils.toString(connection.getInputStream(), connection.getContentEncoding());
    return new JSONObject(content);
}

From source file:ca.christophersaunders.tutorials.sqlite.picasa.PicasaImage.java

private byte[] getBitmapBytesForLocation(String location) {
    try {//w ww . j  a v  a 2 s .c o  m
        URL thumbnailUrl = new URL(location);
        URLConnection conn = thumbnailUrl.openConnection();

        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);

        ByteArrayBuffer imageBytesBuffer = new ByteArrayBuffer(0x2000);
        byte[] buffer = new byte[1024];
        int current = 0;
        while ((current = bis.read(buffer)) != -1) {
            imageBytesBuffer.append(buffer, 0, current);
        }

        byte[] imageBytes = imageBytesBuffer.toByteArray();
        return imageBytes;

    } catch (Exception gottaCatchemAll) {
        Log.w("PicasaImage", "Gotta catch em' all!");
        Log.e("PicasaImage", String.format("Location string was probably bad: %s", location));
        gottaCatchemAll.printStackTrace();
    }
    return new byte[0];
}

From source file:com.cubeia.backoffice.users.phonelookup.strategies.SweEniro.java

private String readHTML() {
    StringBuffer html = new StringBuffer();
    try {/*from w  w w  .j ava2s. c o m*/
        URL url = new URL(BASE_URL + number);
        URLConnection connection = url.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;

        while ((inputLine = in.readLine()) != null) {
            html.append(inputLine);
        }
        in.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return html.toString();
}

From source file:com.domsplace.DomBot.Object.Responders.DomBotWhatWeather.java

@Override
public boolean response(DomBotResponse response, DomBotResponseThread thread) {
    if (!response.getBasicResponse().toLowerCase().startsWith("dombot"))
        return true;
    if (!response.hasArgStartsWith("what"))
        return true;
    if (!response.hasArgStartsWith("weather"))
        return true;
    if (!response.hasArgStartsWith("in"))
        return true;

    String[] args = response.getArgs();
    int index = -1;
    for (int i = 0; i < args.length; i++) {
        if (!args[i].equalsIgnoreCase("in"))
            continue;
        index = i;/*from   w  ww  .  j a v  a2s.  co  m*/
        break;
    }
    if (index < 0)
        return true;
    if (index >= args.length - 1)
        return true;

    String loc = "";
    for (int i = index + 1; i < args.length; i++) {
        loc += args[i] + " ";
    }
    loc = Base.trim(loc, loc.length() - 1);

    loc = loc.replaceAll(", ", ",");
    try {
        loc = "http://api.openweathermap.org/data/2.5/weather?q=" + URLEncoder.encode(loc, "ISO-8859-1");
        URL url = new URL(loc);

        URLConnection urlCon = url.openConnection();

        BufferedReader reader = new BufferedReader(new InputStreamReader(urlCon.getInputStream()));
        String r = reader.readLine();

        JSONObject obj = (JSONObject) JSONValue.parse(r);
        //JSONObject obj = (JSONObject) array.get(0);

        String country = ((JSONObject) obj.get("sys")).get("country").toString();
        String weather = ((JSONObject) ((JSONArray) obj.get("weather")).get(0)).get("main").toString();
        String temp = ((JSONObject) obj.get("main")).get("temp").toString();
        double temperature = Base.getDouble(temp) - 273.15d;
        String location = obj.get("name").toString();

        talk(new String[] { "The weather in " + location + ", " + country + " is " + weather + ", "
                + Base.twoDecimalPlaces(temperature) + "C" });
        return false;
    } catch (Exception ex) {
        talk(new String[] { "I don't know where that is." });
        return false;
    }
}

From source file:com.sxit.crawler.utils.ArchiveUtils.java

/**
 * Get a BufferedReader on the crawler journal given.
 * //from  w ww . j a  va  2 s .  c  o  m
 * @param source URL journal
 * @return journal buffered reader.
 * @throws IOException
 */
public static BufferedReader getBufferedReader(URL source) throws IOException {
    URLConnection conn = source.openConnection();
    boolean isGzipped = conn.getContentType() != null
            && conn.getContentType().equalsIgnoreCase("application/x-gzip")
            || conn.getContentEncoding() != null && conn.getContentEncoding().equalsIgnoreCase("gzip");
    InputStream uis = conn.getInputStream();
    return new BufferedReader(
            isGzipped ? new InputStreamReader(new GZIPInputStream(uis)) : new InputStreamReader(uis));
}

From source file:com.firefly.sample.cast.refplayer.browser.VideoProvider.java

protected JSONObject parseUrl(String urlString) {
    InputStream is = null;/*  w w  w  .  j  a v  a 2s .co m*/
    try {
        java.net.URL url = new java.net.URL(urlString);
        URLConnection urlConnection = url.openConnection();
        is = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream(), "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
        String json = sb.toString();
        return new JSONObject(json);
    } catch (Exception e) {
        Log.d(TAG, "Failed to parse the json for media list", e);
        return null;
    } finally {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:monitoring.tools.ITunesApple.java

private JSONObject urlConnection() throws MalformedURLException, IOException {
    URLConnection connection = new URL(uri + params.getAppId() + uriParams).openConnection();
    connection.getInputStream();
    return new JSONObject(Utils.streamToString(connection.getInputStream()));
}

From source file:de.forsthaus.backend.service.impl.IpToCountryServiceImpl.java

@Override
public int importIP2CountryCSV() {
    try {//from   w w  w .j  a v  a  2  s  .c o m

        // first, delete all records in the ip2Country table
        getIpToCountryDAO().deleteAll();

        final URL url = new URL(this.updateUrl);
        final URLConnection conn = url.openConnection();
        final InputStream istream = conn.getInputStream();

        final ZipInputStream zipInputStream = new ZipInputStream(new BufferedInputStream(istream));

        zipInputStream.getNextEntry();

        final BufferedReader in = new BufferedReader(new InputStreamReader(zipInputStream));

        final CsvBeanReader csvb = new CsvBeanReader(in, CsvPreference.STANDARD_PREFERENCE);

        // List<IpToCountry> list = new ArrayList<IpToCountry>();

        IpToCountry tmp = null;
        int id = 1;
        while (null != (tmp = csvb.read(IpToCountry.class, this.stringNameMapping))) {
            tmp.setId(id++);
            getIpToCountryDAO().saveOrUpdate(tmp);

        }
        // close the stream !!!
        in.close();

        return getIpToCountryDAO().getCountAllIpToCountries();

    } catch (final IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:fr.jayasoft.ivy.url.BasicURLHandler.java

public InputStream openStream(URL url) throws IOException {
    URLConnection conn = null;
    InputStream inStream = null;// w w w.  j a va 2  s  .  c om
    try {
        conn = url.openConnection();
        inStream = conn.getInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        byte[] buffer = new byte[4096];
        int len;
        while ((len = inStream.read(buffer)) > 0) {
            outStream.write(buffer, 0, len);
        }
        return new ByteArrayInputStream(outStream.toByteArray());
    } finally {
        if (inStream != null) {
            inStream.close();
        }

        if (conn != null) {
            if (conn instanceof HttpURLConnection) {
                //System.out.println("Closing HttpURLConnection");
                ((HttpURLConnection) conn).disconnect();
            }
        }
    }
}