List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:com.olacabs.fabric.compute.builder.impl.HttpJarDownloader.java
public Path download(final String url) { HttpGet httpGet = new HttpGet(URI.create(url)); CloseableHttpResponse response = null; try {/* w w w. j av a 2s. co m*/ response = httpClient.execute(httpGet); if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) { throw new RuntimeException(String.format("Server returned [%d][%s] for url: %s", response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), url)); } Header[] headers = response.getHeaders("Content-Disposition"); String filename = null; if (null != headers) { for (Header header : headers) { for (HeaderElement headerElement : header.getElements()) { if (!headerElement.getName().equalsIgnoreCase("attachment")) { continue; } NameValuePair attachment = headerElement.getParameterByName("filename"); if (attachment != null) { filename = attachment.getValue(); } } } } if (Strings.isNullOrEmpty(filename)) { String[] nameParts = url.split("/"); filename = nameParts[nameParts.length - 1]; } return Files.write(Paths.get(this.tmpDirectory, filename), EntityUtils.toByteArray(response.getEntity())); } catch (IOException e) { throw new RuntimeException("Error loading class from: " + url, e); } finally { if (null != response) { try { response.close(); } catch (IOException e) { LOGGER.error("Could not close connection to server: ", e); } } } }
From source file:org.bibimbap.shortcutlink.RestClient.java
/** * Execute the REST subtasks/*from ww w .ja v a2 s . c om*/ */ protected RestClientRequest[] doInBackground(RestClientRequest... params) { // HttpClient that is configured with reasonable default settings and registered schemes for Android final AndroidHttpClient httpClient = AndroidHttpClient.newInstance(RestClient.class.getSimpleName()); for (int index = 0; index < params.length; index++) { RestClientRequest rcr = params[index]; HttpUriRequest httprequest = null; try { HttpResponse httpresponse = null; HttpEntity httpentity = null; // initiating publishProgress(params.length, index, RestfulState.DS_INITIATING); switch (rcr.getHttpRequestType()) { case HTTP_PUT: httprequest = new HttpPut(rcr.getURI()); break; case HTTP_POST: httprequest = new HttpPost(rcr.getURI()); break; case HTTP_DELETE: httprequest = new HttpDelete(rcr.getURI()); break; case HTTP_GET: default: // default to HTTP_GET httprequest = new HttpGet(rcr.getURI()); break; } // resting publishProgress(params.length, index, RestfulState.DS_ONGOING); if ((httpresponse = httpClient.execute(httprequest)) != null) { if ((httpentity = httpresponse.getEntity()) != null) { rcr.setResponse(EntityUtils.toByteArray(httpentity)); } } // success publishProgress(params.length, index, RestfulState.DS_SUCCESS); } catch (Exception ioe) { Log.i(TAG, ioe.getClass().getSimpleName()); // clear out the response rcr.setResponse(null); // abort the request on failure httprequest.abort(); // failed publishProgress(params.length, index, RestfulState.DS_FAILED); } } // close the connection if (httpClient != null) httpClient.close(); return params; }
From source file:com.android.dialer.omni.PlaceUtil.java
/** * Executes a get request and return byte array * @param url the API URL/* w w w. j ava2s. c om*/ * @return the byte array containing the web page * @throws ClientProtocolException * @throws IOException */ public static byte[] getRequest(String url) throws ClientProtocolException, IOException { if (DEBUG) Log.d(TAG, "download: " + url); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 15000); HttpConnectionParams.setSoTimeout(params, 15000); HttpClient client = new DefaultHttpClient(params); HttpGet request = new HttpGet(url); HttpResponse response = client.execute(request); HttpEntity entity = response.getEntity(); byte[] htmlResultPage = null; if (entity != null) { htmlResultPage = EntityUtils.toByteArray(entity); entity.consumeContent(); } return htmlResultPage; }
From source file:com.goliathonline.android.kegbot.util.BitmapUtils.java
/** * Only call this method from the main (UI) thread. The {@link OnFetchCompleteListener} callback * be invoked on the UI thread, but image fetching will be done in an {@link AsyncTask}. * * @param cookie An arbitrary object that will be passed to the callback. *//* ww w .ja v a 2 s . com*/ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); }
From source file:io.wcm.caravan.io.http.impl.RequestUtilTest.java
@Test public void testBuildHttpRequest_Put() throws IOException { byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 }; RequestTemplate template = new RequestTemplate().method("put").append("/path").body(data, null); HttpUriRequest request = RequestUtil.buildHttpRequest("http://host", template.request()); assertEquals("http://host/path", request.getURI().toString()); assertEquals(HttpPut.METHOD_NAME, request.getMethod()); HttpEntityEnclosingRequest entityRequest = (HttpEntityEnclosingRequest) request; assertArrayEquals(data, EntityUtils.toByteArray(entityRequest.getEntity())); }
From source file:org.phpmaven.pear.library.impl.Helper.java
/** * Returns the binary file contents./*from w ww . ja v a2 s. c o m*/ * @param uri URI of the resource. * @return the files content. * @throws IOException thrown on errors. */ public static byte[] getBinaryFileContents(String uri) throws IOException { // is it inside the local filesystem? if (uri.startsWith("file://")) { final File channelFile = new File(uri.substring(7)); final byte[] result = new byte[(int) channelFile.length()]; final FileInputStream fis = new FileInputStream(channelFile); fis.read(result); fis.close(); return result; } // try http connection final HttpClient client = new DefaultHttpClient(); final HttpGet httpget = new HttpGet(uri); final HttpResponse response = client.execute(httpget); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Invalid http status: " + response.getStatusLine().getStatusCode() + " / " + response.getStatusLine().getReasonPhrase()); } final HttpEntity entity = response.getEntity(); if (entity == null) { throw new IOException("Empty response."); } return EntityUtils.toByteArray(entity); }
From source file:tw.idv.gasolin.pycontw2012.util.BitmapUtils.java
/** * Only call this method from the main (UI) thread. The * {@link OnFetchCompleteListener} callback be invoked on the UI thread, but * image fetching will be done in an {@link AsyncTask}. * /*w w w.ja v a2s.c o m*/ * @param cookie * An arbitrary object that will be passed to the callback. */ public static void fetchImage(final Context context, final String url, final BitmapFactory.Options decodeOptions, final Object cookie, final OnFetchCompleteListener callback) { new AsyncTask<String, Void, Bitmap>() { @Override protected Bitmap doInBackground(String... params) { final String url = params[0]; if (TextUtils.isEmpty(url)) { return null; } // First compute the cache key and cache file path for this URL File cacheFile = null; try { MessageDigest mDigest = MessageDigest.getInstance("SHA-1"); mDigest.update(url.getBytes()); final String cacheKey = bytesToHexString(mDigest.digest()); if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + context.getPackageName() + File.separator + "cache" + File.separator + "bitmap_" + cacheKey + ".tmp"); } } catch (NoSuchAlgorithmException e) { // Oh well, SHA-1 not available (weird), don't cache // bitmaps. } if (cacheFile != null && cacheFile.exists()) { Bitmap cachedBitmap = BitmapFactory.decodeFile(cacheFile.toString(), decodeOptions); if (cachedBitmap != null) { return cachedBitmap; } } try { // TODO: check for HTTP caching headers final HttpClient httpClient = SyncService.getHttpClient(context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(url)); final HttpEntity entity = resp.getEntity(); final int statusCode = resp.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK || entity == null) { return null; } final byte[] respBytes = EntityUtils.toByteArray(entity); // Write response bytes to cache. if (cacheFile != null) { try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.w(TAG, "Error writing to bitmap cache: " + cacheFile.toString(), e); } } // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, decodeOptions); } catch (Exception e) { Log.w(TAG, "Problem while loading image: " + e.toString(), e); } return null; } @Override protected void onPostExecute(Bitmap result) { callback.onFetchComplete(cookie, result); } }.execute(url); }
From source file:com.linecorp.armeria.server.http.jetty.JettyServiceTest.java
@Test public void testDefaultHandlerFavicon() throws Exception { try (CloseableHttpClient hc = HttpClients.createMinimal()) { try (CloseableHttpResponse res = hc.execute(new HttpGet(uri("/default/favicon.ico")))) { assertThat(res.getStatusLine().toString(), is("HTTP/1.1 200 OK")); assertThat(res.getFirstHeader(HttpHeaderNames.CONTENT_TYPE.toString()).getValue(), startsWith("image/x-icon")); assertThat(EntityUtils.toByteArray(res.getEntity()).length, is(greaterThan(0))); }// w w w.jav a 2 s. c om } }
From source file:org.apache.http.localserver.EchoHandler.java
/** * Handles a request by echoing the incoming request entity. * If there is no request entity, an empty document is returned. * * @param request the request// w w w . java 2 s . com * @param response the response * @param context the context * * @throws HttpException in case of a problem * @throws IOException in case of an IO problem */ public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!"GET".equals(method) && !"POST".equals(method) && !"PUT".equals(method)) { throw new MethodNotSupportedException(method + " not supported by " + getClass().getName()); } HttpEntity entity = null; if (request instanceof HttpEntityEnclosingRequest) entity = ((HttpEntityEnclosingRequest) request).getEntity(); // For some reason, just putting the incoming entity into // the response will not work. We have to buffer the message. byte[] data; if (entity == null) { data = new byte[0]; } else { data = EntityUtils.toByteArray(entity); } ByteArrayEntity bae = new ByteArrayEntity(data); if (entity != null) { bae.setContentType(entity.getContentType()); } entity = bae; response.setStatusCode(HttpStatus.SC_OK); response.setEntity(entity); }