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:com.example.pierre.applicompanies.library_http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*  w  w  w. j  av  a2s. c  om*/
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
@Override
byte[] getResponseData(HttpEntity entity) throws IOException {

    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        buffer.append(tmp, 0, l);
                        sendProgressDataMessage(copyOfRange(tmp, 0, l));
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.bitfable.ammocache.download.UrlImageDownloader.java

@Override
protected Bitmap download(String key, WeakReference<ImageView> imageViewRef) {
    URL url;//w ww  .  ja  va2  s . c  o  m

    try {
        url = new URL(key);
    } catch (MalformedURLException e) {
        Log.e(TAG, "url is malformed: " + key, e);
        return null;
    }

    HttpURLConnection urlConnection;
    try {
        urlConnection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        Log.e(TAG, "error while opening connection", e);
        return null;
    }

    Bitmap bitmap = null;
    InputStream httpStream = null;
    int contentLength;
    int bytesDownloaded = 0;
    try {
        contentLength = urlConnection.getContentLength();
        httpStream = new FlushedInputStream(urlConnection.getInputStream());
        ByteArrayBuffer baf = new ByteArrayBuffer(BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE);
        byte[] buffer = new byte[BYTE_ARRAY_BUFFER_INCREMENTAL_SIZE];
        while (!isCancelled(imageViewRef)) {
            int incrementalRead = httpStream.read(buffer);
            if (incrementalRead == -1) {
                break;
            }
            bytesDownloaded += incrementalRead;
            if (contentLength > 0 || (bytesDownloaded > 0 && bytesDownloaded == contentLength)) {
                int progress = bytesDownloaded * 100 / contentLength;
                publishProgress(progress, imageViewRef);
            }
            baf.append(buffer, 0, incrementalRead);
        }

        if (isCancelled(imageViewRef))
            return null;

        bitmap = BitmapFactory.decodeByteArray(baf.toByteArray(), 0, baf.length());
    } catch (IOException e) {
        Log.e(TAG, "error creating InputStream", e);
    } finally {
        if (urlConnection != null)
            urlConnection.disconnect();
        if (httpStream != null) {
            try {
                httpStream.close();
            } catch (IOException e) {
                Log.e(TAG, "IOException while closing http stream", e);
            }
        }
    }

    return bitmap;
}

From source file:com.development.androrb.Orband.java

private String loaddata(String Urli) {
    try {//from   www .  j  av a2 s  . c o m
        //Log.i(TAG, " *------ Load Data: "+Urli);
        URLConnection conn;
        conn = new URL(Urli).openConnection();

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

        // loading part
        int current = 0;
        int countix = 0;
        int kbread = 0;
        while ((current = bis.read()) != -1) {
            countix++;
            baf.append((byte) current);

            if (countix >= 1000) {
                countix = 0;
                kbread++;
                TextUpdate = loadingmediadata + " (" + kbread + " kb)";
                runOnUiThread(showTextUpdate);
            }

        }
        // Log.i(TAG, " *------ Load Data done -----*: ");
        html = EncodingUtils.getString(baf.toByteArray(), "UTF-8");
        // ------
    } catch (Exception e) {
        TextUpdate = "Ups, check your Connection ...";
        runOnUiThread(showTextUpdate);
    }

    return html;
}

From source file:me.xiaopan.android.gohttp.BinaryHttpResponseHandler.java

private byte[] toByteArray(HttpRequest httpRequest, final HttpEntity entity) throws IOException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }//w  w w .  j  a  v  a 2  s.  co  m
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return new byte[] {};
    }
    if (entity.getContentLength() > Integer.MAX_VALUE) {
        throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
    }
    int contentLength = (int) entity.getContentLength();
    if (contentLength < 0) {
        contentLength = 4096;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    ByteArrayBuffer buffer = new ByteArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        byte[] tmp = new byte[4096];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = inputStream.read(tmp)) != -1) {
            buffer.append(tmp, 0, readLength);
            completedLength += readLength;
            if (progressListener != null && !httpRequest.isCanceled()
                    && (completedLength >= (callbackNumber + 1) * averageLength
                            || completedLength == contentLength)) {
                callbackNumber++;
                new HttpRequestHandler.UpdateProgressRunnable(httpRequest, contentLength, completedLength)
                        .execute();
            }
        }
    } finally {
        inputStream.close();
    }
    return buffer.toByteArray();
}

From source file:com.aoeng.degu.utils.net.asyncthhpclient.AsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null//from   w  w  w .j a va  2s .  c  om
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) buffersize);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:uk.ac.cam.cl.dtg.picky.parser.pcap2.PcapParser.java

private byte[] toPCAPFormat(Packet packet) {
    ByteArrayBuffer buffer = new ByteArrayBuffer(50);

    ByteBuffer b = ByteBuffer.allocate(16);
    b.order(ByteOrder.LITTLE_ENDIAN);

    // guint32 ts_sec; /* timestamp seconds */
    putUnsignedInt(b, pcap.getTimestamp().getTime() / 1000);

    // guint32 ts_usec; /* timestamp microseconds */
    putUnsignedInt(b, (pcap.getTimestamp().getTime() - pcap.getTimestamp().getTime() / 1000 * 1000));

    // guint32 incl_len; /* number of octets of packet saved in file */
    putUnsignedInt(b, packet.getRawData().length);

    // guint32 orig_len; /* actual length of packet */
    putUnsignedInt(b, packet.length());// w w w .  j a  v a 2 s  .  co m
    // FIXME: putUnsignedInt(b, packet.getOriginalLength());

    buffer.append(b.array(), 0, 16);
    buffer.append(packet.getRawData(), 0, packet.getRawData().length);

    return buffer.toByteArray();
}

From source file:com.example.fertilizercrm.common.httpclient.AsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null//from  w  ww  . j a  va2s.c  o m
 * @return response entity body or null
 * @throws IOException if reading entity or creating byte array failed
 */
byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            if (contentLength < 0) {
                contentLength = BUFFER_SIZE;
            }
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer((int) contentLength);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.flyn.net.asynchttp.AsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null//  w  w w  .  ja v a 2  s.  c  o m
 * @return response entity body or null
 * @throws java.io.IOException if reading entity or creating byte array failed
 */
byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            int buffersize = (contentLength < 0) ? BUFFER_SIZE : (int) contentLength;
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (int) contentLength);
                    }
                } finally {
                    instream.close();
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.chuannuo.tangguo.net.TGHttpResponseHandler.java

byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }/*from w  w w . ja  v  a  2 s .  co m*/
            int buffersize = (contentLength <= 0) ? BUFFER_SIZE : (int) contentLength;
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    long count = 0;
                    int l;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (contentLength <= 0 ? 1 : contentLength));
                    }
                } finally {
                    TGHttpClient.silentCloseInputStream(instream);
                    TGHttpClient.endEntityViaReflection(entity);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}

From source file:com.example.administrator.newsdaily.model.httpclient.AsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/*  w ww.  j  a  v a2  s . co  m*/
 * @return response entity body or null
 * @throws IOException if reading entity or creating byte array failed
 */
byte[] getResponseData(HttpEntity entity) throws IOException {
    byte[] responseBody = null;
    if (entity != null) {
        InputStream instream = entity.getContent();
        if (instream != null) {
            long contentLength = entity.getContentLength();
            if (contentLength > Integer.MAX_VALUE) {
                throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
            }
            int buffersize = (contentLength <= 0) ? BUFFER_SIZE : (int) contentLength;
            try {
                ByteArrayBuffer buffer = new ByteArrayBuffer(buffersize);
                try {
                    byte[] tmp = new byte[BUFFER_SIZE];
                    int l, count = 0;
                    // do not send messages if request has been cancelled
                    while ((l = instream.read(tmp)) != -1 && !Thread.currentThread().isInterrupted()) {
                        count += l;
                        buffer.append(tmp, 0, l);
                        sendProgressMessage(count, (int) (contentLength <= 0 ? 1 : contentLength));
                    }
                } finally {
                    AsyncHttpClient.silentCloseInputStream(instream);
                }
                responseBody = buffer.toByteArray();
            } catch (OutOfMemoryError e) {
                System.gc();
                throw new IOException("File too large to fit into available memory");
            }
        }
    }
    return responseBody;
}