Example usage for org.apache.http.util CharArrayBuffer append

List of usage examples for org.apache.http.util CharArrayBuffer append

Introduction

In this page you can find the example usage for org.apache.http.util CharArrayBuffer append.

Prototype

public void append(ByteArrayBuffer byteArrayBuffer, int i, int i2) 

Source Link

Usage

From source file:Main.java

public static String gzipToString(final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    if (entity == null) {
        throw new IllegalArgumentException("HTTP entity may not be null");
    }//from   w w w. j av  a2s  .  c  o m
    InputStream instream = entity.getContent();
    if (instream == null) {
        return "";
    }
    // gzip logic start
    if (entity.getContentEncoding().getValue().contains("gzip")) {
        instream = new GZIPInputStream(instream);
    }
    // gzip logic end
    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;
    }
    String charset = EntityUtils.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }
    Reader reader = new InputStreamReader(instream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(i);
    try {
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            buffer.append(tmp, 0, l);
        }
    } finally {
        reader.close();
    }
    return buffer.toString();
}

From source file:com.llkj.cm.restfull.network.NetworkConnection.java

/**
 * Transform an InputStream into a String
 * /*from www  .  j  a  v a 2s  .  c o m*/
 * @param is InputStream
 * @return String from the InputStream
 * @throws IOException If a problem occurs while reading the InputStream
 */
private static String convertStreamToString(final InputStream is, final boolean isGzipEnabled, final int method,
        final int contentLength) throws IOException {
    InputStream cleanedIs = is;
    if (isGzipEnabled) {
        cleanedIs = new GZIPInputStream(is);
    }

    try {
        switch (method) {
        case METHOD_GET:
        case METHOD_DELETE: {
            final BufferedReader reader = new BufferedReader(new InputStreamReader(cleanedIs));
            final StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();
        }
        case METHOD_POST:
        case METHOD_PUT: {
            int i = contentLength;
            if (i < 0) {
                i = 4096;
            }

            final Reader reader = new InputStreamReader(cleanedIs);
            final CharArrayBuffer buffer = new CharArrayBuffer(i);
            final char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }

            return buffer.toString();
        }
        default:
            return null;
        }
    } finally {
        cleanedIs.close();

        if (isGzipEnabled) {
            is.close();
        }
    }
}

From source file:com.android.aft.AFNetworkConnection.AFNetworkConnection.java

/**
 * Transform an InputStream into a String
 *
 * @param is InputStream/* w w w.ja  v  a 2  s. c o m*/
 * @return String from the InputStream
 * @throws IOException If a problem occurs while reading the InputStream
 */
public static String convertStreamToString(InputStream is, boolean isGzipEnabled, HttpMethod method,
        int contentLength) throws IOException {
    InputStream cleanedIs = is;
    if (isGzipEnabled) {
        cleanedIs = new GZIPInputStream(is);
    }

    try {
        switch (method) {
        case Get:
            final BufferedReader reader = new BufferedReader(new InputStreamReader(cleanedIs));
            final StringBuilder sb = new StringBuilder();

            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            return sb.toString();

        case Post:
            int i = contentLength;
            if (i < 0) {
                i = 4096;
            }

            final Reader readerPost = new InputStreamReader(cleanedIs);
            final CharArrayBuffer buffer = new CharArrayBuffer(i);
            final char[] tmp = new char[1024];
            int l;
            while ((l = readerPost.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
            return buffer.toString();

        default:
            return null;
        }
    } finally {
        cleanedIs.close();

        if (isGzipEnabled) {
            is.close();
        }
    }
}

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

private String toString(HttpRequest httpRequest, final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return "";
    }// ww w . ja va  2s .  c  o m
    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;
    }
    String charset = getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    Reader reader = new InputStreamReader(inputStream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        char[] tmp = new char[1024];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = reader.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 {
        reader.close();
    }
    return buffer.toString();
}

From source file:org.vietspider.net.apache.AbstractSessionInputBuffer.java

private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos) throws IOException {
    int off = this.bufferpos;
    int len;//from w w w . j  av  a2  s  .  c o  m
    this.bufferpos = pos + 1;
    if (pos > 0 && this.buffer[pos - 1] == HTTP.CR) {
        // skip CR if found
        pos--;
    }
    len = pos - off;
    if (this.ascii) {
        charbuffer.append(this.buffer, off, len);
    } else {
        String s = new String(this.buffer, off, len, this.charset);
        charbuffer.append(s);
    }
    return len;
}

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

private String toString(HttpRequest httpRequest, final HttpEntity entity, final String defaultCharset)
        throws IOException, ParseException {
    InputStream inputStream = entity.getContent();
    if (inputStream == null) {
        return "";
    }//from   w  w w.  ja v a 2s.c o  m
    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;
    }
    String charset = StringHttpResponseHandler.getContentCharSet(entity);
    if (charset == null) {
        charset = defaultCharset;
    }
    if (charset == null) {
        charset = HTTP.DEFAULT_CONTENT_CHARSET;
    }

    long averageLength = contentLength / httpRequest.getProgressCallbackNumber();
    int callbackNumber = 0;
    Reader reader = new InputStreamReader(inputStream, charset);
    CharArrayBuffer buffer = new CharArrayBuffer(contentLength);
    HttpRequest.ProgressListener progressListener = httpRequest.getProgressListener();
    try {
        char[] tmp = new char[1024];
        int readLength;
        long completedLength = 0;
        while (!httpRequest.isStopReadData() && (readLength = reader.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 {
        reader.close();
    }
    return buffer.toString();
}

From source file:at.general.solutions.android.ical.remote.HttpDownloadThread.java

@Override
public void run() {
    HttpParams params = new BasicHttpParams();
    ConnManagerParams.setMaxTotalConnections(params, 100);
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setUserAgent(params, USER_AGENT);

    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));

    ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
    DefaultHttpClient client = new DefaultHttpClient(cm, params);

    if (useAuthentication) {
        client.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                new UsernamePasswordCredentials(remoteUsername, remotePassword));
    }//from   www.ja  v  a 2 s.  c  o m

    HttpGet get = new HttpGet(remoteUrl);

    try {
        super.sendInitMessage(R.string.downloading);

        HttpResponse response = client.execute(get);
        Log.d(LOG_TAG, response.getStatusLine().getReasonPhrase() + " "
                + isGoodResponse(response.getStatusLine().getStatusCode()));
        if (isGoodResponse(response.getStatusLine().getStatusCode())) {
            HttpEntity entity = response.getEntity();

            InputStream instream = entity.getContent();
            if (instream == null) {
                super.sendErrorMessage(R.string.couldnotConnectToRemoteserver);
                return;
            }
            if (entity.getContentLength() > Integer.MAX_VALUE) {
                super.sendErrorMessage(R.string.remoteFileTooLarge);
                return;
            }
            int i = (int) entity.getContentLength();
            if (i < 0) {
                i = 4096;
            }
            String charset = EntityUtils.getContentCharSet(entity);
            if (charset == null) {
                charset = encoding;
            }
            if (charset == null) {
                charset = HTTP.DEFAULT_CONTENT_CHARSET;
            }
            Reader reader = new InputStreamReader(instream, charset);
            CharArrayBuffer buffer = new CharArrayBuffer(i);

            super.sendMaximumMessage(i);

            try {
                char[] tmp = new char[1024];
                int l;
                while ((l = reader.read(tmp)) != -1) {
                    buffer.append(tmp, 0, l);
                    super.sendProgressMessage(buffer.length());
                }
            } finally {
                reader.close();
            }

            super.sendFinishedMessage(buffer.toString());
        } else {
            int errorMsg = R.string.couldnotConnectToRemoteserver;
            if (isAccessDenied(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.accessDenied;
            } else if (isFileNotFound(response.getStatusLine().getStatusCode())) {
                errorMsg = R.string.remoteFileNotFound;
            }
            super.sendErrorMessage(errorMsg);
        }
    } catch (UnknownHostException e) {
        super.sendErrorMessage(R.string.unknownHostException, e);
        Log.e(LOG_TAG, "Error occured", e);
    } catch (Throwable e) {
        super.sendErrorMessage(R.string.couldnotConnectToRemoteserver, e);
        Log.e(LOG_TAG, "Error occured", e);
    }

    finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:com.subgraph.vega.ui.httpeditor.parser.ParserBase.java

/**
 * Get the next line of characters from a CharArrayBuffer into another CharArrayBuffer. Treats LF and CRLF as valid
 * line delimiters. Treats the entire buffer as a line if no line delimiters are found.
 * //from  www  .  ja va  2 s . c  o  m
 * @param src Source buffer to read line from.
 * @param srcCursor Parser cursor for src. Adjusted to discard line delimiters.
 * @param dst Destination buffer for characters from line. 
 * @return Number of characters in line minus line delimiters, or < 0 if none found.
 */
protected int readLine(final CharArrayBuffer src, final ParserCursor srcCursor, final CharArrayBuffer dst) {
    if (srcCursor.atEnd()) {
        return -1;
    }

    int idxPos = srcCursor.getPos();
    int idxLf = src.indexOf(HTTP.LF, idxPos, srcCursor.getUpperBound());
    int idxEnd;

    if (idxLf > 0) {
        if (src.charAt(idxLf - 1) == HTTP.CR) {
            idxEnd = idxLf - 1;
        } else {
            idxEnd = idxLf;
        }
    } else {
        idxEnd = srcCursor.getUpperBound();
        idxLf = idxEnd - 1;
    }

    dst.append(src, idxPos, idxEnd - idxPos);
    srcCursor.updatePos(idxLf + 1);
    return idxEnd - idxPos;
}

From source file:im.delight.android.webrequest.WebRequest.java

protected String parseResponse(HttpResponse response) throws Exception {
    final Header contentEncoding = response.getFirstHeader("Content-Encoding");
    // if we have a compressed response (GZIP)
    if (contentEncoding != null && contentEncoding.getValue() != null
            && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
        // get the entity and the content length (if any) from the response
        final HttpEntity entity = response.getEntity();
        long contentLength = entity.getContentLength();

        // handle too large or undefined content lengths
        if (contentLength > Integer.MAX_VALUE) {
            throw new Exception("Response too large");
        } else if (contentLength < 0) {
            // use an arbitrary buffer size
            contentLength = 4096;/*w  w  w.ja va2 s  .  co  m*/
        }

        // construct a GZIP input stream from the response
        InputStream responseStream = entity.getContent();
        if (responseStream == null) {
            return null;
        }
        responseStream = new GZIPInputStream(responseStream);

        // read from the stream
        Reader reader = new InputStreamReader(responseStream, mCharset);
        CharArrayBuffer buffer = new CharArrayBuffer((int) contentLength);
        try {
            char[] tmp = new char[1024];
            int l;
            while ((l = reader.read(tmp)) != -1) {
                buffer.append(tmp, 0, l);
            }
        } finally {
            reader.close();
        }

        // return the decompressed response text as a string
        return buffer.toString();
    }
    // if we have an uncompressed response
    else {
        // return the response text as a string
        return EntityUtils.toString(response.getEntity(), mCharset);
    }
}

From source file:org.vietspider.net.apache.AbstractSessionInputBuffer.java

private int lineFromLineBuffer(final CharArrayBuffer charbuffer) throws IOException {
    // discard LF if found
    int l = this.linebuffer.length();
    if (l > 0) {
        if (this.linebuffer.byteAt(l - 1) == HTTP.LF) {
            l--;//from ww w  .  j a  v  a2  s  .  c o  m
            this.linebuffer.setLength(l);
        }
        // discard CR if found
        if (l > 0) {
            if (this.linebuffer.byteAt(l - 1) == HTTP.CR) {
                l--;
                this.linebuffer.setLength(l);
            }
        }
    }
    l = this.linebuffer.length();
    if (this.ascii) {
        charbuffer.append(this.linebuffer, 0, l);
    } else {
        String s = new String(this.linebuffer.buffer(), 0, l, this.charset);
        charbuffer.append(s);
    }
    return l;
}