Example usage for org.apache.http.util ByteArrayBuffer toByteArray

List of usage examples for org.apache.http.util ByteArrayBuffer toByteArray

Introduction

In this page you can find the example usage for org.apache.http.util ByteArrayBuffer toByteArray.

Prototype

public byte[] toByteArray() 

Source Link

Usage

From source file:subhan.portal.config.Util.java

public static void downloadFromUrl(String downloadUrl, String fileName) throws IOException {
    File root = android.os.Environment.getExternalStorageDirectory(); // path ke sdcard

    File dir = new File(root.getAbsolutePath() + "/youread"); // path ke folder

    if (dir.exists() == false) { // cek folder eksistensi
        dir.mkdirs(); // kalau belum ada, dibuat
    }// w  w  w.j  av  a  2s  .  c  om

    URL url = new URL(downloadUrl); // you can write here any link
    File file = new File(dir, fileName);

    // 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(5000);
    int current = 0;
    while ((current = bis.read()) != -1) {
        baf.append((byte) current);
    }

    // Convert the Bytes read to a String. 
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
}

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 w w.  j a  va2s . c om*/
 * @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:pl.lewica.util.FileUtil.java

public static boolean fetchAndSaveImage(String sourceUrl, String destinationPath, boolean overwrite)
        throws IOException {
    File destinationFile = new File(destinationPath);
    if (destinationFile.exists() && !overwrite) {
        return false;
    }/* w  ww.  java2 s . co m*/

    BufferedInputStream bis = null;
    FileOutputStream fos = null;

    try {
        URL url = new URL(sourceUrl);
        // See http://stackoverflow.com/questions/3498643/dalvik-message-default-buffer-size-used-in-bufferedinputstream-constructor-it/7516554#7516554
        int bufferSize = 8192;
        bis = new BufferedInputStream(url.openStream(), bufferSize);
        ByteArrayBuffer bab = new ByteArrayBuffer(50);

        int current = 0;
        while ((current = bis.read()) != -1) {
            bab.append((byte) current);
        }

        fos = new FileOutputStream(destinationFile);
        fos.write(bab.toByteArray());
        fos.close();
    } catch (MalformedURLException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ioe) {
                // This issue can be safely skipped but there's no harm in logging it
                Log.w("FileUtil", "Unable to close file output stream for " + sourceUrl);
            }
        }
        if (bis != null) {
            try {
                bis.close();
            } catch (IOException ioe) {
                // This issue can be safely skipped but there's no harm in logging it
                Log.w("FileUtil", "Unable to close buffered input stream for " + sourceUrl);
            }
        }
    }

    return true;
}

From source file:com.fastbootmobile.encore.api.common.HttpGet.java

/**
 * Downloads the data from the provided URL.
 * @param inUrl The URL to get from/*from   ww w . j  a v a  2  s.  c  o  m*/
 * @param query The query field. '?' + query will be appended automatically, and the query data
 *              MUST be encoded properly.
 * @return A byte array of the data
 */
public static byte[] getBytes(String inUrl, String query, boolean cached)
        throws IOException, RateLimitException {
    final String formattedUrl = inUrl + (query.isEmpty() ? "" : ("?" + query));

    Log.d(TAG, "Formatted URL: " + formattedUrl);

    URL url = new URL(formattedUrl);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setRequestProperty("User-Agent", "OmniMusic/1.0-dev (http://www.omnirom.org)");
    urlConnection.setUseCaches(cached);
    urlConnection.setInstanceFollowRedirects(true);
    int maxStale = 60 * 60 * 24 * 28; // tolerate 4-weeks stale
    urlConnection.addRequestProperty("Cache-Control", "max-stale=" + maxStale);
    try {
        final int status = urlConnection.getResponseCode();
        // MusicBrainz returns 503 Unavailable on rate limit errors. Parse the JSON anyway.
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(urlConnection.getInputStream());
            int contentLength = urlConnection.getContentLength();
            if (contentLength <= 0) {
                // No length? Let's allocate 100KB.
                contentLength = 100 * 1024;
            }
            ByteArrayBuffer bab = new ByteArrayBuffer(contentLength);
            BufferedInputStream bis = new BufferedInputStream(in);
            int character;

            while ((character = bis.read()) != -1) {
                bab.append(character);
            }
            return bab.toByteArray();
        } else if (status == HttpURLConnection.HTTP_NOT_FOUND) {
            // 404
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_FORBIDDEN) {
            return new byte[] {};
        } else if (status == HttpURLConnection.HTTP_UNAVAILABLE) {
            throw new RateLimitException();
        } else if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == 307 /* HTTP/1.1 TEMPORARY REDIRECT */
                || status == HttpURLConnection.HTTP_SEE_OTHER) {
            // We've been redirected, follow the new URL
            final String followUrl = urlConnection.getHeaderField("Location");
            Log.e(TAG, "Redirected to: " + followUrl);
            return getBytes(followUrl, "", cached);
        } else {
            Log.e(TAG, "Error when fetching: " + formattedUrl + " (" + urlConnection.getResponseCode() + ")");
            return new byte[] {};
        }
    } finally {
        urlConnection.disconnect();
    }
}

From source file:fr.itinerennes.utils.IOUtils.java

/**
 * Reads the given input stream and returns it as an array of bytes.
 * /*from w  w  w.ja v  a 2  s. c  o m*/
 * @param in
 *            an input stream to read
 * @return an array of bytes with the content provided by the given input stream
 */
public static byte[] readBytes(final InputStream in) {

    final byte[] buffer = new byte[BYTE_BUF_SIZE];
    final ByteArrayBuffer bytes = new ByteArrayBuffer(10 * BYTE_BUF_SIZE);
    int len = 0;
    try {
        while ((len = in.read(buffer)) != -1) {
            bytes.append(buffer, 0, len);
        }
    } catch (final IOException e) {
        LOGGER.error("unable to read the input stream", e);
    }

    return bytes.toByteArray();
}

From source file:bala.padio.Settings.java

public static String DownloadFromUrl(String u) {
    try {/*from w ww.  j a  va 2 s.  co  m*/
        URL url = new URL(u);
        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);
        }

        return new String(baf.toByteArray());

    } catch (Exception e) {
        Log.e(TAG, "Error: " + e);
    }
    return null;
}

From source file:mobisocial.musubi.social.FacebookFriendFetcher.java

public static byte[] getImageFromURL(String remoteUrl) {
    try {/* w  ww  .  ja va2  s .c o m*/
        // Grab the content
        URL url = new URL(remoteUrl);
        URLConnection ucon = url.openConnection();
        InputStream is = ucon.getInputStream();

        // Read the content chunk by chunk
        BufferedInputStream bis = new BufferedInputStream(is, 8192);
        ByteArrayBuffer baf = new ByteArrayBuffer(0);
        byte[] chunk = new byte[CHUNK_SIZE];
        int current = bis.read(chunk);
        while (current != -1) {
            baf.append(chunk, 0, current);
            current = bis.read(chunk);
        }
        return baf.toByteArray();
    } catch (IOException e) {
        Log.e(TAG, "HTTP error", e);
    }
    return null;
}

From source file:com.seo.support.http.EntityUtils.java

/**
 * Read the contents of an entity and return it as a byte array.
 *
 * @param entity/*w  w w .  j a  v a 2s .  co m*/
 * @return byte array containing the entity content. May be null if
 *   {@link HttpEntity#getContent()} is null.
 * @throws IOException if an error occurs reading the input stream
 * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
 */
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }
    InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }
    try {
        if (entity.getContentLength() > Integer.MAX_VALUE) {
            throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
        }
        int i = (int) entity.getContentLength();
        if (i < 0) {
            i = 4096;
        }
        ByteArrayBuffer buffer = new ByteArrayBuffer(i);
        byte[] tmp = new byte[4096];
        int l;
        while ((l = instream.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
        return buffer.toByteArray();
    } finally {
        instream.close();
    }
}

From source file:com.BibleQuote.utils.FsUtils.java

public static boolean loadContentFromURL(String fromURL, String toFile) {
    try {/*from   w w  w. ja v a2  s  . c o m*/
        URL url = new URL("http://bible-desktop.com/xml" + fromURL);
        File file = new File(toFile);

        /* 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(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            baf.append((byte) current);
        }

        /* Convert the Bytes read to a String. */
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(baf.toByteArray());
        fos.close();

    } catch (IOException e) {
        Log.e(TAG, String.format("loadContentFromURL(%1$s, %2$s)", fromURL, toFile), e);
        return false;
    }

    return true;
}

From source file:ota.otaupdates.utils.Utils.java

public static void DownloadFromUrl(String download_url, String fileName) {
    final String TAG = "Downloader";

    if (!isMainThread()) {
        try {//from  ww  w .ja  v  a  2s.  c  om
            URL url = new URL(download_url);

            if (!new File(DL_PATH).isDirectory()) {
                if (!new File(DL_PATH).mkdirs()) {
                    Log.e(TAG, "Creating the directory " + DL_PATH + "failed");
                }
            }

            File file = new File(DL_PATH + fileName);

            long startTine = System.currentTimeMillis();
            Log.d(TAG, "Beginning download of " + url.getPath() + " to " + DL_PATH + fileName);

            /*
             * Open a connection and define Streams
             */
            URLConnection ucon = url.openConnection();
            InputStream is = ucon.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);

            /*
             * Read bytes until there is nothing left
             */
            ByteArrayBuffer baf = new ByteArrayBuffer(50);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }

            /* Convert Bytes to a String */
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baf.toByteArray());
            fos.close();

            Log.d(TAG,
                    "Download finished in " + ((System.currentTimeMillis() - startTine) / 1000) + " seconds");
        } catch (Exception e) {
            Log.e(TAG, "Error: " + e);
            e.printStackTrace();
        }
    } else {
        Log.e(TAG, "Tried to run in Main Thread. Aborting...");
    }
}