List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:de.yaio.services.metaextract.client.MetaExtractClient.java
/** * create a metaextract of the file// w w w . j a v a 2s.c om * @return returns the metaextract as JSON * @param fileName file to make a metaextract from * @throws IOExceptionWithCause if something went wrong with metaextract * @throws IOException if something went wrong with response-io */ public byte[] getMetaExtractFromFile(final String fileName) throws IOExceptionWithCause, IOException { // get metadata from file Map<String, String> params = new HashMap<String, String>(); params.put("lang", "de"); Map<String, String> binfileParams = new HashMap<String, String>(); binfileParams.put("file", fileName); // call url String baseUrl = metaextracturl + "/getByFile"; HttpEntity entity; HttpResponse response; response = HttpUtils.callPostUrlPure(baseUrl, metaextractusername, metaextractpassword, params, null, binfileParams); entity = response.getEntity(); // check response int retCode = response.getStatusLine().getStatusCode(); if (retCode < 200 || retCode > 299) { throw new IOExceptionWithCause("error while extracting metadata for file", fileName, new IOException("illegal reponse:" + response.getStatusLine() + " for baseurl:" + baseUrl + " with file:" + fileName + " response:" + EntityUtils.toString(entity))); } return EntityUtils.toByteArray(entity); }
From source file:org.openqa.selenium.remote.internal.ApacheHttpAsyncClient.java
/** Same implementation as {@link ApacheHttpClient#createResponse(org.apache.http.HttpResponse, HttpContext)} */ private HttpResponse createResponse(org.apache.http.HttpResponse response, HttpContext context) throws IOException { HttpResponse internalResponse = new HttpResponse(); internalResponse.setStatus(response.getStatusLine().getStatusCode()); for (Header header : response.getAllHeaders()) { for (HeaderElement headerElement : header.getElements()) { internalResponse.addHeader(header.getName(), headerElement.getValue()); }// w ww. java 2 s.c o m } HttpEntity entity = response.getEntity(); if (entity != null) { try { internalResponse.setContent(EntityUtils.toByteArray(entity)); } finally { EntityUtils.consume(entity); } } Object host = context.getAttribute(HTTP_TARGET_HOST); if (host instanceof HttpHost) { internalResponse.setTargetHost(((HttpHost) host).toURI()); } return internalResponse; }
From source file:com.blork.anpod.util.BitmapUtils.java
public static BitmapResult fetchImage(Context context, Picture picture, int desiredWidth, int desiredHeight) { // First compute the cache key and cache file path for this URL File cacheFile = null;//from w ww . j ava 2 s. c om if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { Log.d("APOD", "creating cache file"); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (prefs.getBoolean("archive", false)) { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "APOD" + File.separator + toSlug(picture.title) + ".jpg"); } else { cacheFile = new File(Environment.getExternalStorageDirectory() + File.separator + "Android" + File.separator + "data" + File.separator + "com.blork.anpod" + File.separator + "cache" + File.separator + toSlug(picture.title) + ".jpg"); } } else { Log.d("APOD", "SD card not mounted"); Log.d("APOD", "creating cache file"); cacheFile = new File(context.getCacheDir() + File.separator + toSlug(picture.title) + ".jpg"); } if (cacheFile != null && cacheFile.exists()) { Log.d("APOD", "Cache file exists, using it."); try { Bitmap bitmap = decodeStream(new FileInputStream(cacheFile), desiredWidth, desiredHeight); return new BitmapResult(bitmap, Uri.fromFile(cacheFile)); } catch (FileNotFoundException e) { } } try { Log.d("APOD", "Not cached, fetching"); BitmapUtils.manageCache(toSlug(picture.title), context); // TODO: check for HTTP caching headers final HttpClient httpClient = SyncUtils.getHttpClient(context.getApplicationContext()); final HttpResponse resp = httpClient.execute(new HttpGet(picture.getFullSizeImageUrl())); 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); Log.d("APOD", "Writing cache file " + cacheFile.getName()); try { cacheFile.getParentFile().mkdirs(); cacheFile.createNewFile(); FileOutputStream fos = new FileOutputStream(cacheFile); fos.write(respBytes); fos.close(); } catch (FileNotFoundException e) { Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e); } catch (IOException e) { Log.d("APOD", "Error writing to bitmap cache: " + cacheFile.toString(), e); } // Decode the bytes and return the bitmap. Log.d("APOD", "Reiszing bitmap image"); Bitmap bitmap = decodeStream(new ByteArrayInputStream(respBytes), desiredWidth, desiredHeight); Log.d("APOD", "Returning bitmap image"); return new BitmapResult(bitmap, Uri.fromFile(cacheFile)); } catch (Exception e) { Log.d("APOD", "Problem while loading image: " + e.toString(), e); } return null; }
From source file:com.swisscom.refimpl.boundary.MIB3Client.java
public EasypayResponse modifyAuthSubscription(String merchantId, String easypayAuthId, String operation) throws IOException, HttpException { HttpPut method = null;// ww w . j a va2 s . c o m try { method = new HttpPut(MIB3Client.AUTHSUBSCRIPTIONS_URL + "/" + easypayAuthId); String entity = "{\"operation\": \"" + operation + "\"}"; method.setEntity(new StringEntity(entity, ContentType.create("application/vnd.ch.swisscom.easypay.authsubscription+json", "UTF-8"))); addSignature(method, "PUT", "/authsubscriptions/" + easypayAuthId, merchantId, "application/vnd.ch.swisscom.easypay.authsubscription+json", entity.getBytes("UTF-8")); HttpResponse response = httpClient.execute(method); return new EasypayResponse(new String(EntityUtils.toByteArray(response.getEntity())), response.getStatusLine().getStatusCode()); } finally { if (method != null) { method.releaseConnection(); } ; } }
From source file:zz.pseas.ghost.client.GhostClient.java
public CommonsPage postForPage(String url, Map<String, String> params) { HttpPost post = new HttpPost(url); ArrayList<NameValuePair> arr = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { arr.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); }//from ww w .j a v a 2 s .c o m CommonsPage commonsPage = new CommonsPage(); try { UrlEncodedFormEntity entity = new UrlEncodedFormEntity(arr, "utf-8"); post.setEntity(entity); CloseableHttpResponse resp = client.execute(post, context); Header[] headers = resp.getAllHeaders(); for (Header h : headers) { String k = h.getName(); String v = h.getValue(); commonsPage.addHeader(k, v); } byte[] bytes = EntityUtils.toByteArray(resp.getEntity()); commonsPage.setContents(bytes); } catch (Exception e) { commonsPage.setErrMsg(e.getMessage()); } finally { post.releaseConnection(); } return commonsPage; }
From source file:com.github.avarabyeu.restendpoint.http.DefaultErrorHandler.java
/** * Parses byte from entity// w w w . j a v a 2 s . c o m * * @param rs HTTP Response * @return Body as byte array * @throws RestEndpointIOException In case of request error */ private byte[] getErrorBody(HttpResponse rs) throws RestEndpointIOException { HttpEntity entity = null; try { entity = rs.getEntity(); return EntityUtils.toByteArray(rs.getEntity()); } catch (IOException e) { throw new RestEndpointIOException("Unable to read body from error", e); } finally { EntityUtils.consumeQuietly(entity); } }
From source file:de.badw.strauss.glyphpicker.controller.bitmap.BitmapUrlLoader.java
/** * Gets an image from a URL.// w w w.j a va 2 s . co m * * @param url the url * @return the image from the url */ public BufferedImage getImageFromUrl(String url) { SystemDefaultHttpClient httpClient = new SystemDefaultHttpClient(); try { HttpGet httpGet = new HttpGet(url); HttpResponse response = httpClient.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); byte[] bytes = EntityUtils.toByteArray(entity); return ImageIO.read(new ByteArrayInputStream(bytes)); } else { throw new IOException( "Download failed, HTTP response code " + statusCode + " - " + statusLine.getReasonPhrase()); } } catch (IOException e) { LOGGER.warn("Error loading image from \"" + url + "\". " + e.getMessage()); } finally { httpClient.getConnectionManager().shutdown(); } return null; }
From source file:de.yaio.commons.http.HttpUtils.java
/** * execute POST-Request for url with params * @param baseUrl the url to call * @param username username for auth * @param password password for auth * @param params params for the request * @param textFileParams text-files to upload * @param binFileParams bin-files to upload * @return Response-Text as ByteArray * @throws IOException possible Exception if Request-state <200 > 299 *///from w ww.ja va 2 s. co m public static byte[] callPostUrl(final String baseUrl, final String username, final String password, final Map<String, String> params, final Map<String, String> textFileParams, final Map<String, String> binFileParams) throws IOException { // create request HttpResponse response = callPostUrlPure(baseUrl, username, password, params, textFileParams, binFileParams); // get response int retCode = response.getStatusLine().getStatusCode(); if (retCode < 200 || retCode > 299) { throw new IOException("illegal reponse:" + response.getStatusLine() + " for urlcall:" + baseUrl); } HttpEntity entity = response.getEntity(); return EntityUtils.toByteArray(entity); }
From source file:org.s1.testing.httpclient.TestHttpClient.java
/** * * @param u/* w w w .j a va 2 s . co m*/ * @param data * @param headers * @return */ public HttpResponseBean get(String u, Map<String, Object> data, Map<String, String> headers) { if (headers == null) headers = new HashMap<String, String>(); u = getURL(u, data); HttpGet get = new HttpGet(u); try { for (String h : headers.keySet()) { get.setHeader(h, headers.get(h)); } //HttpPost post = new HttpPost(LOGIN_URL); client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Test Browser"); client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //client.getParams().setParameter(ClientPNames.COOKIE_POLICY, org.apache.http.client.params.CookiePolicy.BROWSER_COMPATIBILITY); HttpResponse resp = null; try { resp = client.execute(host, get, context); } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } Map<String, String> rh = new HashMap<String, String>(); for (Header h : resp.getAllHeaders()) { rh.put(h.getName(), h.getValue()); } try { HttpResponseBean r = new HttpResponseBean(resp.getStatusLine().getStatusCode(), rh, EntityUtils.toByteArray(resp.getEntity())); printIfError(u, r); return r; } catch (IOException e) { throw new RuntimeException(e.getMessage(), e); } } finally { get.releaseConnection(); } }
From source file:net.monofraps.gradlebukkit.tasks.DownloadCraftBukkit.java
private void downloadArtifact(final String url, final String referenceMd5) throws IOException, LifecycleExecutionException { getLogger().lifecycle("Going to download CraftBukkit from " + url); final HttpGet httpGet = new HttpGet(url); final HttpClient httpClient = HttpClientBuilder.create().build(); final HttpResponse httpResponse = httpClient.execute(httpGet); if (!bukkitServerJar.exists()) { if (!bukkitServerJar.createNewFile()) throw new LifecycleExecutionException("Failed to create bukkit server jar " + bukkitServerJar); }// w w w . j a va 2 s. c om final HttpEntity httpEntity = httpResponse.getEntity(); getLogger().lifecycle("Writing " + httpEntity.getContentLength() + " bytes to bukkit.jar"); final byte[] data = EntityUtils.toByteArray(httpEntity); FileUtils.writeByteArrayToFile(bukkitServerJar, data); final String localMd5 = DigestUtils.md5Hex(new FileInputStream(bukkitServerJar)); if (!localMd5.equals(referenceMd5)) { throw new LifecycleExecutionException("bukkit.jar MD5 sum mismatch. - Download failed."); } }