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.tweetlanes.android.core.URLFetch.java

public static void fetchBitmap(final String urlAsString, final FetchBitmapCallback callback) {

    Thread t = new Thread() {

        public void run() {
            URL url;//from w w  w  .  ja v a  2s . co m
            Bitmap bitmap = null;
            try {
                url = new URL(urlAsString);
                // Log.d("tweetlanes url fetch", urlAsString);
                URLConnection connection = url.openConnection();
                connection.setUseCaches(true);
                Object response = connection.getContent();
                if (response instanceof Bitmap) {
                    bitmap = (Bitmap) response;
                } else {
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (callback != null) {
                callback.finished(bitmap != null ? true : false, bitmap);
            }
        }
    };
    t.start();
}

From source file:com.norconex.commons.lang.url.URLStreamer.java

private static InputStream responseInputStream(URLConnection conn) throws IOException {
    conn.connect();//from   w  w  w.j  av a  2  s.c  om
    return new AutoCloseInputStream(conn.getInputStream());
}

From source file:com.shafiq.mytwittle.URLFetch.java

public static void fetchBitmap(final String urlAsString, final FetchBitmapCallback callback) {

    Thread t = new Thread() {

        @Override/*w  w  w  . ja  va  2  s.co m*/
        public void run() {
            URL url;
            Bitmap bitmap = null;
            try {
                url = new URL(urlAsString);
                // Log.d("mytwittle url fetch", urlAsString);
                URLConnection connection = url.openConnection();
                connection.setUseCaches(true);
                Object response = connection.getContent();
                if (response instanceof Bitmap) {
                    bitmap = (Bitmap) response;
                } else {
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (callback != null) {
                callback.finished(bitmap != null ? true : false, bitmap);
            }
        }
    };
    t.start();
}

From source file:com.tweetlanes.android.URLFetch.java

public static void fetchBitmap(final String urlAsString, final FetchBitmapCallback callback) {

    Thread t = new Thread() {
        public void run() {
            URL url;/*from  w  ww  .j  a v  a 2  s. c  o m*/
            Bitmap bitmap = null;
            try {
                url = new URL(urlAsString);
                //Log.d("tweetlanes url fetch", urlAsString);
                URLConnection connection = url.openConnection();
                connection.setUseCaches(true);
                Object response = connection.getContent();
                if (response instanceof Bitmap) {
                    bitmap = (Bitmap) response;
                } else {
                    InputStream inputStream = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                }
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (callback != null) {
                callback.finished(bitmap != null ? true : false, bitmap);
            }
        }
    };
    t.start();
}

From source file:com.agc.tmdb.Util.URLFetcher.java

/**
 * Can be used to Fetch the URL, where URL is Java.net.URL.
 * @param url//from   ww  w.j  a  va2s. c  o  m
 * @return
 * @throws TMDbException
 */
public static String fetch(URL url) throws TMDbException {
    System.out.println("URL: " + url);
    StringWriter content = null;

    try {
        content = new StringWriter();

        BufferedReader in = null;
        URLConnection connectionObject = null;
        try {
            connectionObject = openConnection(url);
            setBrowserProperties(connectionObject);

            in = new BufferedReader(
                    new InputStreamReader(connectionObject.getInputStream(), getCharset(connectionObject)));
            String line;
            while ((line = in.readLine()) != null) {
                content.write(line);
            }
        } finally {
            if (in != null) {
                in.close();
            }

            if (connectionObject instanceof HttpURLConnection) {
                ((HttpURLConnection) connectionObject).disconnect();
            }
        }
        return content.toString();
    } catch (IOException ex) {
        throw new TMDbException(TMDbExceptionTypes.EXCEPTION_CONNECTION_ERROR, null, ex);
    } finally {
        if (content != null) {
            try {
                content.close();
            } catch (IOException ex) {
                throw new TMDbException(TMDbExceptionTypes.EXCEPTION_CONNECTION_ERROR,
                        "Failed to Close the connection.", ex);
            }
        }
    }
}

From source file:com.example.shutapp.DatabaseHandler.java

private static boolean downloadDatabase(Context context) {
    try {/* w  w  w.  j  a va  2 s  .c o  m*/
        Log.d(TAG, "downloading database");
        URL url = new URL(StringLiterals.SERVER_DB_URL);
        /* Open a connection to that URL. */
        URLConnection ucon = url.openConnection();
        /*
         * Define InputStreams to read from the URLConnection.
         */
        InputStream is = ucon.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        /*
         * Read bytes to the Buffer until there is nothing more to read(-1).
         */
        ByteArrayBuffer baf = new ByteArrayBuffer(StringLiterals.DATABASE_BUFFER);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = null;
        // Select storage location
        fos = context.openFileOutput("db_name.s3db", Context.MODE_PRIVATE);

        fos.write(baf.toByteArray());
        fos.close();
        Log.d(TAG, "downloaded");
    } catch (IOException e) {
        String exception = e.toString();
        Log.e(TAG, "downloadDatabase Error: " + exception);
        return false;
    } catch (Exception e) {
        String exception = e.toString();
        Log.e(TAG, "downloadDatabase Error: " + exception);
        return false;
    }
    return true;
}

From source file:co.raveesh.yspages.YSScraper.java

/**
 * Returns individual company information. Currently limited to returning only addresses
 * @param company The company's individual JSONObject
 * @return company JSONObject with obtained data added to it
 * @throws IOException Thrown in case of error getting data from website
 * @throws XPatherException Thrown in case of error with evaluation of XPath
 * @throws JSONException Thrown in case of error putting or retrieving JSON data
 *//*from www.  j a  v  a2  s.c  o  m*/
public static JSONObject scrapeIndividualCompanyInformation(JSONObject company)
        throws IOException, XPatherException, JSONException {
    HtmlCleaner cleaner = new HtmlCleaner();
    CleanerProperties props = cleaner.getProperties();
    props.setAllowHtmlInsideAttributes(true);
    props.setAllowMultiWordAttributes(true);
    props.setRecognizeUnicodeChars(true);
    props.setOmitComments(true);

    URL url = new URL(company.getString("page"));
    System.out.println("Getting data for company:" + company.getString("name"));
    System.out.println("Company page:" + company.getString("page"));
    URLConnection conn = url.openConnection();
    TagNode node = cleaner.clean(new InputStreamReader(conn.getInputStream()));
    Object[] companyAddresses = node.evaluateXPath("//div[@class='singleoffice']");

    JSONArray addresses = new JSONArray();
    for (int i = 0; i < companyAddresses.length; i++) {
        TagNode address = (TagNode) companyAddresses[i];
        Object[] spans = address.evaluateXPath("//span");
        String headline = "", city = "", detail = "";
        if (spans.length > 0) {
            headline = ((TagNode) spans[0]).getText().toString().trim().replaceAll("\n", "").replaceAll("\r",
                    "");
        }
        if (spans.length > 1) {
            city = ((TagNode) spans[1]).getText().toString().trim().replaceAll("\n", "").replaceAll("\r", "");
        }
        Object[] longaddress = address.evaluateXPath("//span[@class='longaddress']");
        if (longaddress.length > 0) {
            detail = ((TagNode) longaddress[0]).getText().toString().trim().replaceAll("\n", "")
                    .replaceAll("\r", "");
        }

        JSONObject individualAddress = new JSONObject();
        individualAddress.put("headline", headline);
        individualAddress.put("city", city);
        individualAddress.put("detail", detail);
        boolean blank = true;
        if (!detail.equals("")) {
            JSONObject latlong = getLatLong(readJsonFromUrl(Constants.GOOGLE_GECODE_BASE_URL
                    + detail.replace(".", "").replace(",", "%20").replace(" ", "%20").replace("#", "")));
            if (latlong.has("lat")) {
                individualAddress.put("latlong", latlong);
                blank = false;
            }
        }
        if (!city.equals("") && blank) {
            individualAddress.put("latlong", getLatLong(readJsonFromUrl(Constants.GOOGLE_GECODE_BASE_URL
                    + city.replace(".", "").replace(",", "%20").replace(" ", "%20").replace("#", ""))));
        }
        addresses.put(individualAddress);
    }
    company.put("addresses", addresses);
    return company;
}

From source file:com.zack6849.alphabot.api.Utils.java

public static String google(String s) {
    try {/*from www . ja va 2s  .  co  m*/
        String temp = String.format("https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=%s",
                URLEncoder.encode(s, "UTF-8"));
        URL u = new URL(temp);
        URLConnection c = u.openConnection();
        c.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17");
        BufferedReader in = new BufferedReader(new InputStreamReader(c.getInputStream()));
        String json = "";
        String tmp;
        while ((tmp = in.readLine()) != null) {
            json += tmp + "\n";
        }
        in.close();
        JsonElement jelement = new JsonParser().parse(json);
        JsonObject output = jelement.getAsJsonObject();
        output = output.getAsJsonObject("responseData").getAsJsonArray("results").get(0).getAsJsonObject();

        String title = StringEscapeUtils.unescapeJava(StringEscapeUtils
                .unescapeHtml4(output.get("titleNoFormatting").toString().replaceAll("\"", "")));
        String content = StringEscapeUtils.unescapeJava(StringEscapeUtils.unescapeHtml4(output.get("content")
                .toString().replaceAll("\\s+", " ").replaceAll("\\<.*?>", "").replaceAll("\"", "")));
        String url = StringEscapeUtils.unescapeJava(output.get("url").toString().replaceAll("\"", ""));
        String result = String.format("Google: %s | %s | (%s)", title, content, url);
        if (result != null) {
            return result;
        } else {
            return "No results found for query " + s;
        }
    } catch (IOException ex) {
        Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

From source file:crow.util.Util.java

public static String urlGet(String url) throws IOException {
    URLConnection conn = new URL(url).openConnection();
    conn.setConnectTimeout(20000);//from ww w  . j  av a  2  s .c  o  m
    InputStream input = conn.getInputStream();
    String result = inputStreamToString(input);
    return result;
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.JSONParser.java

/**
 * Download URL data to String.//ww w .j av a2 s. c o m
 *
 * @param msgsUrl URL to download
 * @return data string
 */
private static String loadURLData(String msgsUrl) {
    try {
        URL url = new URL(msgsUrl);
        URLConnection conn = url.openConnection();
        InputStreamReader streamReader = new InputStreamReader(conn.getInputStream());

        BufferedReader br = new BufferedReader(streamReader);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append("\n");
        }
        br.close();
        String resp = sb.toString();

        return resp;
    } catch (IOException iOEx) {
        Log.d("", "");

        return "";
    }
}