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.sinelead.car.club.NewsFragment.java

public String getZipString(org.apache.http.HttpResponse response) {

    String resultString = "";
    ByteArrayBuffer bt = new ByteArrayBuffer(4096);
    try {/*from w w  w  .  ja v  a  2  s  . c  o m*/
        // Get
        HttpEntity he = response.getEntity();
        // 
        GZIPInputStream gis = new GZIPInputStream(he.getContent());
        int l;
        byte[] tmp = new byte[4096];
        while ((l = gis.read(tmp)) != -1) {
            bt.append(tmp, 0, l);
        }

        resultString = new String(bt.toByteArray(), "utf-8");
        // UTF-8

    } catch (Exception e) {
        Log.i("ERR", e.toString()); // 
    }

    return resultString;
}

From source file:com.android.yijiang.kzx.http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null// w w  w  .  j av  a2s  .  com
 * @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;
                    // 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));
                    }
                } 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.gvccracing.android.tttimer.Tabs.RaceInfoTab.java

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(
            "http://www.gvccracing.com/?page_id=2525&pass=com.gvccracing.android.tttimer");

    try {//from  w ww .j  a va2s . com
        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        InputStream is = response.getEntity().getContent();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(20);

        int current = 0;

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

        /* Convert the Bytes read to a String. */
        String text = new String(baf.toByteArray());

        JSONObject mainJson = new JSONObject(text);
        JSONArray jsonArray = mainJson.getJSONArray("members");

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.getJSONObject(i);

            String firstName = json.getString("fname");
            String lastName = json.getString("lname");
            String licenseStr = json.getString("license");
            Integer license = 0;
            try {
                license = Integer.parseInt(licenseStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse license string");
            }
            long age = json.getLong("age");
            String categoryStr = json.getString("category");
            Integer category = 5;
            try {
                category = Integer.parseInt(categoryStr);
            } catch (Exception ex) {
                Log.e(LOG_TAG(), "Unable to parse category string");
            }
            String phone = json.getString("phone");
            long phoneNumber = 0;
            try {
                phoneNumber = Long.parseLong(phone.replace("-", "").replace("(", "").replace(")", "")
                        .replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse phone number");
            }
            String gender = json.getString("gender");
            String econtact = json.getString("econtact");
            String econtactPhone = json.getString("econtact_phone");
            long eContactPhoneNumber = 0;
            try {
                eContactPhoneNumber = Long.parseLong(econtactPhone.replace("-", "").replace("(", "")
                        .replace(")", "").replace(" ", "").replace(".", "").replace("*", ""));
            } catch (Exception e) {
                Log.e(LOG_TAG(), "Unable to parse econtact phone number");
            }
            Long member_id = json.getLong("member_id");

            String gvccCategory;
            switch (category) {
            case 1:
            case 2:
            case 3:
                gvccCategory = "A";
                break;
            case 4:
                gvccCategory = "B4";
                break;
            case 5:
                gvccCategory = "B5";
                break;
            default:
                gvccCategory = "B5";
                break;
            }

            Log.w(LOG_TAG(), lastName);
            Cursor racerInfo = Racer.Instance().Read(getActivity(),
                    new String[] { Racer._ID, Racer.FirstName, Racer.LastName, Racer.USACNumber,
                            Racer.PhoneNumber, Racer.EmergencyContactName, Racer.EmergencyContactPhoneNumber },
                    Racer.USACNumber + "=?", new String[] { license.toString() }, null);
            if (racerInfo.getCount() > 0) {
                racerInfo.moveToFirst();
                Long racerID = racerInfo.getLong(racerInfo.getColumnIndex(Racer._ID));
                Racer.Instance().Update(getActivity(), racerID, firstName, lastName, license, 0l, phoneNumber,
                        econtact, eContactPhoneNumber, gender);
                Cursor racerClubInfo = RacerClubInfo.Instance().Read(getActivity(),
                        new String[] { RacerClubInfo._ID, RacerClubInfo.GVCCID, RacerClubInfo.RacerAge,
                                RacerClubInfo.Category },
                        RacerClubInfo.Racer_ID + "=? AND " + RacerClubInfo.Year + "=? AND "
                                + RacerClubInfo.Upgraded + "=?",
                        new String[] { racerID.toString(), "2013", "0" }, null);
                if (racerClubInfo.getCount() > 0) {
                    racerClubInfo.moveToFirst();
                    long racerClubInfoID = racerClubInfo
                            .getLong(racerClubInfo.getColumnIndex(RacerClubInfo._ID));
                    String rciCategory = racerClubInfo
                            .getString(racerClubInfo.getColumnIndex(RacerClubInfo.Category));

                    boolean upgraded = gvccCategory != rciCategory;
                    if (upgraded) {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, null, null, upgraded);
                        RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0,
                                0, age, member_id, false);
                    } else {
                        RacerClubInfo.Instance().Update(getActivity(), racerClubInfoID, null, null, null, null,
                                null, null, null, age, member_id, upgraded);
                    }

                } else {
                    RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0,
                            age, member_id, false);
                }
                if (racerClubInfo != null) {
                    racerClubInfo.close();
                }
            } else {
                // TODO: Better birth date
                Uri resultUri = Racer.Instance().Create(getActivity(), firstName, lastName, license, 0l,
                        phoneNumber, econtact, eContactPhoneNumber, gender);
                long racerID = Long.parseLong(resultUri.getLastPathSegment());
                RacerClubInfo.Instance().Create(getActivity(), racerID, null, 2013, gvccCategory, 0, 0, 0, age,
                        member_id, false);
            }
            if (racerInfo != null) {
                racerInfo.close();
            }
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        Log.e(LOG_TAG(), e.getMessage());
    }
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {/*w ww  .ja  v a  2s  .c om*/
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Get a SAXParser from the SAXPArserFactory.
            SAXParserFactory spf = SAXParserFactory.newInstance();
            SAXParser sp = spf.newSAXParser();

            // Get the XMLReader of the SAXParser we created.
            XMLReader xr = sp.getXMLReader();

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

From source file:crawler.Page.java

/**
 * Read contents from an entity, with a specified maximum. This is a replacement of
 * EntityUtils.toByteArray because that function does not impose a maximum size.
 *
 * @param entity The entity from which to read
 * @param maxBytes The maximum number of bytes to read
 * @return A byte array containing maxBytes or fewer bytes read from the entity
 *
 * @throws IOException Thrown when reading fails for any reason
 *///w  w  w .j ava2  s .  c o m
protected byte[] toByteArray(HttpEntity entity, int maxBytes) throws IOException {
    if (entity == null) {
        return new byte[0];
    }
    try (InputStream is = entity.getContent()) {
        int size = (int) entity.getContentLength();
        int readBufferLength = size;

        if (readBufferLength <= 0) {
            readBufferLength = 4096;
        }
        // in case when the maxBytes is less than the actual page size
        readBufferLength = Math.min(readBufferLength, maxBytes);

        // We allocate the buffer with either the actual size of the entity (if available)
        // or with the default 4KiB if the server did not return a value to avoid allocating
        // the full maxBytes (for the cases when the actual size will be smaller than maxBytes).
        ByteArrayBuffer buffer = new ByteArrayBuffer(readBufferLength);

        byte[] tmpBuff = new byte[4096];
        int dataLength;

        while ((dataLength = is.read(tmpBuff)) != -1) {
            if (maxBytes > 0 && (buffer.length() + dataLength) > maxBytes) {
                truncated = true;
                dataLength = maxBytes - buffer.length();
            }
            buffer.append(tmpBuff, 0, dataLength);
            if (truncated) {
                break;
            }
        }
        return buffer.toByteArray();
    }
}

From source file:com.digitalpebble.stormcrawler.protocol.okhttp.HttpProtocol.java

private final byte[] toByteArray(final ResponseBody responseBody, MutableBoolean trimmed) throws IOException {

    if (responseBody == null)
        return new byte[] {};

    final InputStream instream = responseBody.byteStream();
    if (instream == null) {
        return null;
    }//from w w  w  .ja v  a2  s .com
    if (responseBody.contentLength() > Integer.MAX_VALUE) {
        throw new IOException("Cannot buffer entire body for content length: " + responseBody.contentLength());
    }
    int reportedLength = (int) responseBody.contentLength();
    // set default size for buffer: 100 KB
    int bufferInitSize = 102400;
    if (reportedLength != -1) {
        bufferInitSize = reportedLength;
    }
    // avoid init of too large a buffer when we will trim anyway
    if (maxContent != -1 && bufferInitSize > maxContent) {
        bufferInitSize = maxContent;
    }
    long endDueFor = -1;
    if (completionTimeout != -1) {
        endDueFor = System.currentTimeMillis() + (completionTimeout * 1000);
    }
    final ByteArrayBuffer buffer = new ByteArrayBuffer(bufferInitSize);
    final byte[] tmp = new byte[4096];
    int lengthRead;
    while ((lengthRead = instream.read(tmp)) != -1) {
        // check whether we need to trim
        if (maxContent != -1 && buffer.length() + lengthRead > maxContent) {
            buffer.append(tmp, 0, maxContent - buffer.length());
            trimmed.setValue(true);
            break;
        }
        buffer.append(tmp, 0, lengthRead);
        // check whether we hit the completion timeout
        if (endDueFor != -1 && endDueFor <= System.currentTimeMillis()) {
            trimmed.setValue(true);
            break;
        }
    }
    return buffer.toByteArray();
}

From source file:com.letv.commonjar.http.HttpJsonCallBack.java

/**
 * /* ww w. j av a2  s  .co m*/
 * @param entity
 * @return
 * @throws IOException
 */
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);
                        onProgress(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:net.yacy.cora.protocol.http.HTTPClient.java

/**
 * Return entity content loaded as a byte array
 * @param entity HTTP entity//w  ww. j a v  a 2  s .  co  m
 * @param maxBytes maximum bytes to read. -1 means no maximum limit.
 * @return content bytes or null when entity content is null.
 * @throws IOException when a read error occured or content length is over maxBytes
 */
public static byte[] getByteArray(final HttpEntity entity, int maxBytes) throws IOException {
    final InputStream instream = entity.getContent();
    if (instream == null) {
        return null;
    }
    try {
        long contentLength = entity.getContentLength();
        /*
         * When no maxBytes is specified, the default limit is
         * Integer.MAX_VALUE as a byte array size can not be over
         */
        if (maxBytes < 0) {
            maxBytes = Integer.MAX_VALUE;
        }
        /*
         * Content length may already be known now : check it before
         * downloading
         */
        if (contentLength > maxBytes) {
            throw new IOException(
                    "Content to download exceed maximum value of " + Formatter.bytesToString(maxBytes));
        }
        int initialSize = Math.min(maxBytes, (int) contentLength);
        /* ContentLenght may be negative because unknown for now */
        if (initialSize < 0) {
            initialSize = 4096;
        }
        final ByteArrayBuffer buffer = new ByteArrayBuffer(initialSize);
        byte[] tmp = new byte[4096];
        int l = 0;
        /* Sum is a long to enable check against Integer.MAX_VALUE */
        long sum = 0;
        while ((l = instream.read(tmp)) != -1) {
            sum += l;
            /*
             * Check total length while downloading as content length might
             * not be known at beginning
             */
            if (sum > maxBytes) {
                throw new IOException(
                        "Download exceeded maximum value of " + Formatter.bytesToString(maxBytes));
            }
            buffer.append(tmp, 0, l);
        }
        return buffer.toByteArray();
    } catch (final OutOfMemoryError e) {
        throw new IOException(e.toString());
    } finally {
        instream.close();
    }
}

From source file:cn.com.loopj.android.http.DataAsyncHttpResponseHandler.java

/**
 * Returns byte array of response HttpEntity contents
 *
 * @param entity can be null/* ww  w.ja va  2s  .c om*/
 * @return response entity body or null
 * @throws 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, 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.development.androrb.listfolders.java

private String loaddata(String Urli) {
    try {//w  ww  . ja  v a 2 s.  c o  m
        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;

        while ((current = bis.read()) != -1) {

            baf.append((byte) current);
        }
        //Log.i(TAG, " *------ after while -----*: "+current);
        html = EncodingUtils.getString(baf.toByteArray(), "UTF-8");

    } catch (Exception e) {
        TextUpdate = "Ups, check your Connection ...";
        runOnUiThread(showTextUpdate);

        //Toast.makeText(this, "Shit, Loading Error!", Toast.LENGTH_SHORT).show();
    }

    return html;
}