List of usage examples for org.apache.http.util ByteArrayBuffer append
public void append(CharArrayBuffer charArrayBuffer, int i, int i2)
From source file:com.flyn.net.asynchttp.DataAsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null/*www . j a v a 2s . 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 { 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.android.yijiang.kzx.http.DataAsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null//from www . j av a2 s . co m * @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:cn.com.loopj.android.http.DataAsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null/*w w w .j a v a 2 s . c o m*/ * @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.example.pierre.applicompanies.library_http.DataAsyncHttpResponseHandler.java
/** * Returns byte array of response HttpEntity contents * * @param entity can be null//from w ww . j a v a 2s.c o m * @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:net.reichholf.dreamdroid.helpers.SimpleHttpClient.java
/** * @param uri// ww w .jav a 2 s . c om * @param parameters * @return */ public boolean fetchPageContent(String uri, List<NameValuePair> parameters) { // Set login, ssl, port, host etc; applyConfig(); mErrorText = ""; mErrorTextId = -1; mError = false; mBytes = new byte[0]; if (!uri.startsWith("/")) { uri = "/".concat(uri); } HttpURLConnection conn = null; try { if (mProfile.getSessionId() != null) parameters.add(new BasicNameValuePair("sessionid", mProfile.getSessionId())); URL url = new URL(buildUrl(uri, parameters)); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(mConnectionTimeoutMillis); if (DreamDroid.featurePostRequest()) conn.setRequestMethod("POST"); setAuth(conn); if (conn.getResponseCode() != 200) { if (conn.getResponseCode() == HttpURLConnection.HTTP_BAD_METHOD && mRememberedReturnCode != HttpURLConnection.HTTP_BAD_METHOD) { // Method not allowed, the target device either can't handle // POST or GET requests (old device or Anti-Hijack enabled) DreamDroid.setFeaturePostRequest(!DreamDroid.featurePostRequest()); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_BAD_METHOD; return fetchPageContent(uri, parameters); } if (conn.getResponseCode() == HttpURLConnection.HTTP_PRECON_FAILED && mRememberedReturnCode != HttpURLConnection.HTTP_PRECON_FAILED) { createSession(); conn.disconnect(); mRememberedReturnCode = HttpURLConnection.HTTP_PRECON_FAILED; return fetchPageContent(uri, parameters); } mRememberedReturnCode = 0; Log.e(LOG_TAG, Integer.toString(conn.getResponseCode())); switch (conn.getResponseCode()) { case HttpURLConnection.HTTP_UNAUTHORIZED: mErrorTextId = R.string.auth_error; break; default: mErrorTextId = -1; } mErrorText = conn.getResponseMessage(); mError = true; return false; } BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); ByteArrayBuffer baf = new ByteArrayBuffer(50); int read = 0; int bufSize = 512; byte[] buffer = new byte[bufSize]; while ((read = bis.read(buffer)) != -1) { baf.append(buffer, 0, read); } mBytes = baf.toByteArray(); if (DreamDroid.dumpXml()) dumpToFile(url); return true; } catch (MalformedURLException e) { mError = true; mErrorTextId = R.string.illegal_host; } catch (UnknownHostException e) { mError = true; mErrorText = null; mErrorTextId = R.string.host_not_found; } catch (ProtocolException e) { mError = true; mErrorText = e.getLocalizedMessage(); } catch (ConnectException e) { mError = true; mErrorTextId = R.string.host_unreach; } catch (IOException e) { e.printStackTrace(); mError = true; mErrorText = e.getLocalizedMessage(); } finally { if (conn != null) conn.disconnect(); if (mError) if (mErrorText == null) mErrorText = "Error text is null"; Log.e(LOG_TAG, mErrorText); } return false; }
From source file:com.letv.commonjar.http.HttpJsonCallBack.java
/** * /*from w ww.java 2s . com*/ * @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:com.tapcentive.sdk.touchpoint.nfc.SEManager.java
/** * Send and receive.//from w w w .ja v a2 s. c o m * * @param cmd the cmd * @return the data that was read or null if an error occurred */ public byte[] sendAndReceive(byte[] cmd) { byte[] result; byte[] fullBytes = null; ByteArrayBuffer fullresult = new ByteArrayBuffer(255); boolean hasMore = true; byte[] command = cmd; boolean gotSuccessSW = false; long time1 = SystemClock.uptimeMillis(); while (hasMore) { try { result = partialSendAndReceive(command); fullresult.append(result, 0, result.length - 2); if (result.length < 2) { Log.d(TAG, "READ command issue"); return null; } // Check if more data is available from touchpoint if (result[result.length - 2] == (byte) 0x61) { hasMore = true; } else { if (result[result.length - 2] != (byte) 0x90) { Log.d(TAG, "Bad SW on READ (command/response):" + ApduUtil.getHexString(command, 0, command.length, "") + " / " + ApduUtil.getHexString(result, 0, result.length, "")); return null; /*throw new TapcentiveException("An error occurred. Please try again and if this problem persists contact customer service");*/ } else { // SW 9000 hasMore = false; gotSuccessSW = true; } } command = getResponse; // After the first iteration change the command header to a GET RESPONSE } catch (IOException e) { e.printStackTrace(); return null; } } long time2 = SystemClock.uptimeMillis(); Log.d(TAG, "TIME: send&Receive: " + (time2 - time1)); /*if (!gotSuccessSW){ throw new TapcentiveException("An error occurred. Please try again and if this problem persists contact customer service"); }*/ if (gotSuccessSW) { fullBytes = fullresult.toByteArray(); Log.d(TAG, "TIME: send&receive apdu size: " + fullBytes.length); } return fullBytes; }
From source file:com.vuze.android.remote.AndroidUtils.java
public static boolean readInputStreamIfStartWith(InputStream is, ByteArrayBuffer bab, byte[] startsWith) throws IOException { byte[] buffer = new byte[32 * 1024]; boolean first = true; try {// w w w . j a v a 2 s . c o m while (true) { int len = is.read(buffer); if (len <= 0) { break; } bab.append(buffer, 0, len); if (first) { first = false; for (int i = 0; i < startsWith.length; i++) { if (startsWith[i] != buffer[i]) { return false; } } } } return bab.isEmpty() ? false : true; } finally { is.close(); } }
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 a v a 2s. com 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:nu.nethome.home.items.web.proxy.HomeCloudConnection.java
private HttpResponse performLocalRequest(HttpRequest request) throws IOException { HttpResponse httpResponse;//from ww w . j a va2 s . c om HttpURLConnection connection = (HttpURLConnection) new URL(localURL + request.url).openConnection(); for (String header : request.headers) { String parts[] = header.split(":"); connection.setRequestProperty(parts[0].trim(), parts[1].trim()); } ByteArrayBuffer baf = new ByteArrayBuffer(50); try (InputStream response = connection.getInputStream()) { BufferedInputStream bis = new BufferedInputStream(response); int read; int bufSize = 512; byte[] buffer = new byte[bufSize]; while (true) { read = bis.read(buffer); if (read == -1) { break; } baf.append(buffer, 0, read); } } catch (IOException e) { return new HttpResponse(systemId, "", new String[0], CHALLENGE); } Map<String, List<String>> map = connection.getHeaderFields(); String headers[] = new String[map.size()]; int i = 0; for (Map.Entry<String, List<String>> entry : map.entrySet()) { System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue()); headers[i++] = entry.getKey() + ":" + entry.getValue().get(0); } httpResponse = new HttpResponse(systemId, new String(Base64.encodeBase64(baf.toByteArray())), headers, CHALLENGE); return httpResponse; }