List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:org.tinymediamanager.scraper.util.Url.java
/** * Gets the input stream./*from w w w. j a v a 2 s . c o m*/ * * @return the input stream * @throws IOException * Signals that an I/O exception has occurred. */ public InputStream getInputStream() throws IOException, InterruptedException { // workaround for local files if (url.startsWith("file:")) { String newUrl = url.replace("file:/", ""); File file = new File(newUrl); return new FileInputStream(file); } BasicHttpContext localContext = new BasicHttpContext(); ByteArrayInputStream is = null; // replace our API keys for logging... String logUrl = url.replaceAll("api_key=\\w+", "api_key=<API_KEY>").replaceAll("api/\\d+\\w+", "api/<API_KEY>"); LOGGER.debug("getting " + logUrl); HttpGet httpget = new HttpGet(uri); RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000) .build(); httpget.setConfig(requestConfig); // set custom headers for (Header header : headersRequest) { httpget.addHeader(header); } CloseableHttpResponse response = null; try { response = client.execute(httpget, localContext); headersResponse = response.getAllHeaders(); entity = response.getEntity(); responseStatus = response.getStatusLine(); if (entity != null) { is = new ByteArrayInputStream(EntityUtils.toByteArray(entity)); } EntityUtils.consume(entity); } catch (InterruptedIOException e) { LOGGER.info("aborted request (" + e.getMessage() + "): " + logUrl); throw e; } catch (UnknownHostException e) { LOGGER.error("proxy or host not found/reachable", e); throw e; } catch (Exception e) { LOGGER.error("Exception getting url " + logUrl, e); } finally { if (response != null) { response.close(); } } return is; }
From source file:com.k42b3.aletheia.response.html.Images.java
private byte[] requestImage(URL imageUrl, int count) { byte[] image = null; try {// ww w . ja va 2 s . co m if (count > 4) { throw new Exception("Max redirection reached"); } DefaultHttpClient client = new DefaultHttpClient(); HttpUriRequest request = new HttpGet(imageUrl.toString()); HttpResponse response = client.execute(request); // redirect Header location = response.getFirstHeader("Location"); if (location != null) { URL url = new URL(location.getValue()); if (!url.toString().equals(imageUrl.toString())) { return requestImage(url, count + 1); } } // read image image = EntityUtils.toByteArray(response.getEntity()); // info imagesLoaded++; lblInfo.setText("Loading images (" + (imagesLoaded) + " / " + images.size() + ")"); } catch (Exception e) { Aletheia.handleException(e); } return image; }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
@Test @SuppressWarnings("deprecation") public void testStringEntity() throws Exception { StringEntity myEntity = new StringEntity("important message", "UTF-8"); System.out.println(myEntity.getContentType() + ""); System.out.println(myEntity.getContentLength() + ""); System.out.println(EntityUtils.getContentCharSet(myEntity)); System.out.println(EntityUtils.toString(myEntity)); System.out.println(EntityUtils.toByteArray(myEntity).length + ""); }
From source file:com.life.wuhan.util.ImageDownloader.java
private Bitmap downloadBitmap(final String imageUrl) { // AndroidHttpClient is not allowed to be used from the main thread final HttpClient client = new DefaultHttpClient(); // ??/*from ww w .j a v a 2s. c o m*/ if (NetworkUtil.getNetworkType(mContext) == NetworkUtil.APN_CMWAP) { HttpHost proxy = new HttpHost(NetworkUtil.getHostIp(), NetworkUtil.getHostPort()); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } final HttpGet getRequest = new HttpGet(imageUrl); try { HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { final byte[] respBytes = EntityUtils.toByteArray(entity); writeImageFile(imageUrl, entity, respBytes); // Decode the bytes and return the bitmap. return BitmapFactory.decodeByteArray(respBytes, 0, respBytes.length, null); } } catch (IOException e) { getRequest.abort(); } catch (OutOfMemoryError e) { clearCache(); System.gc(); } catch (IllegalStateException e) { getRequest.abort(); } catch (Exception e) { getRequest.abort(); } finally { } return null; }
From source file:org.s1.testing.httpclient.TestHttpClient.java
/** * * @param u/*w ww. j a va 2s . c o m*/ * @param data * @param headers * @return */ public HttpResponseBean postForm(String u, Map<String, Object> data, Map<String, String> headers) { if (headers == null) headers = new HashMap<String, String>(); u = getURL(u, null); HttpPost post = new HttpPost(u); try { headers.put("Content-Type", "application/x-www-form-urlencoded"); for (String h : headers.keySet()) { post.setHeader(h, "" + headers.get(h)); } //HttpPost post = new HttpPost(LOGIN_URL); List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>(); if (data != null) { for (String h : data.keySet()) { params.add(new BasicNameValuePair(h, (String) data.get(h))); } } UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(params, Charset.forName("UTF-8")); post.setEntity(urlEncodedFormEntity); 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, post, 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 { post.releaseConnection(); } }
From source file:edu.ucsb.nceas.ezid.EZIDService.java
/** * Log into the EZID service using account credentials provided by EZID. The cookie * returned by EZID is cached in a local CookieStore for the duration of the EZIDService, * and so subsequent calls uning this instance of the service will function as * fully authenticated. An exception is thrown if authentication fails. * @param username to identify the user account from EZID * @param password the secret password for this account * @throws EZIDException if authentication fails for any reason *//* w w w . j a v a 2s . com*/ public void login(String username, String password) throws EZIDException { try { URI serviceUri = new URI(loginServiceEndpoint); HttpHost targetHost = new HttpHost(serviceUri.getHost(), serviceUri.getPort(), serviceUri.getScheme()); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()), new UsernamePasswordCredentials(username, password)); AuthCache authCache = new BasicAuthCache(); BasicScheme basicAuth = new BasicScheme(); authCache.put(targetHost, basicAuth); HttpClientContext localcontext = HttpClientContext.create(); localcontext.setAuthCache(authCache); localcontext.setCredentialsProvider(credsProvider); ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { public byte[] handleResponse(HttpResponse response) throws ClientProtocolException, IOException { HttpEntity entity = response.getEntity(); if (entity != null) { return EntityUtils.toByteArray(entity); } else { return null; } } }; byte[] body = null; HttpGet httpget = new HttpGet(loginServiceEndpoint); body = httpclient.execute(httpget, handler, localcontext); String message = new String(body); String msg = parseIdentifierResponse(message); } catch (URISyntaxException e) { throw new EZIDException(e.getMessage()); } catch (ClientProtocolException e) { throw new EZIDException(e.getMessage()); } catch (IOException e) { throw new EZIDException(e.getMessage()); } }
From source file:org.ubicompforall.cityexplorer.gui.PoiDetailsActivity.java
/** * Method fetches information for the current PoI, and shows it in the GUI. * @param poi The poi to fetch information from. *//* w w w .j av a 2 s. c om*/ private void showPoiDetails(Poi poi) { title.setText(poi.getLabel()); description.setText(poi.getDescription()); // address.setText( poi.getAddress().getStreet() + "\n" + poi.getAddress().getZipCode() + "\n" + poi.getAddress().getCity()); // ZIP code removed address.setText(poi.getAddress().getStreet() + "\n" + poi.getAddress().getCity()); category.setText(poi.getCategory()); telephone.setText(poi.getTelephone()); openingHours.setText(poi.getOpeningHours()); webPage.setText(poi.getWebPage()); if (!poi.getImageURL().equals("")) { final String imageURL = poi.getImageURL(); new Thread(new Runnable() { public void run() { try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(imageURL); //have user-inserted url HttpResponse httpResponse; final HttpEntity entity; httpResponse = httpClient.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = httpResponse.getEntity(); // TODO: The picture is not shown on Honeycomb SDK or higher (web service calls should be made on a separate thread) // Code should be upgraded to use the Async Task if (entity != null) { //converting into bytemap and inserting into imageView poiImage.post(new Runnable() { public void run() { byte[] imageBytes = new byte[0]; try { imageBytes = EntityUtils.toByteArray(entity); } catch (Throwable t) { debug(0, "t is " + t); // t.printStackTrace(); } poiImage.setImageBitmap( BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length)); } }); } else { debug(0, "entity == null?"); } } else { debug(0, "(httpResponse.getStatusLine().getStatusCode() == not OK "); } } catch (UnknownHostException e) { //Toast.makeText(PoiDetailsActivity.this, "Enable Internet to show Picture", Toast.LENGTH_SHORT ); debug(0, "Enable Internet to show Picture: " + imageURL); } catch (Exception e) { debug(-1, "Error fetching image: " + imageURL); e.printStackTrace(); } //try-catch }//run }//new Runnable class ).start(); } else { poiImage.setImageBitmap(null); } //if img, else blank }
From source file:com.traffic.common.utils.http.HttpClientUtils.java
/** * ,result""/*from ww w.j a v a2s .c o m*/ * * @param url * @param param * @return */ public static String httpGet(String url) { logger.info("httpGet URL [" + url + "] start "); HttpClient httpclient = null; HttpGet httpGet = null; HttpResponse response = null; HttpEntity entity = null; String result = ""; try { httpclient = HttpConnectionManager.getHttpClient(); // cookie---?? httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpGet = new HttpGet(url); // ??? for (Entry<String, String> entry : headers.entrySet()) { httpGet.setHeader(entry.getKey(), entry.getValue()); } response = httpclient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { logger.error("HttpStatus ERROR" + "Method failed: " + response.getStatusLine()); return ""; } else { entity = response.getEntity(); if (null != entity) { byte[] bytes = EntityUtils.toByteArray(entity); result = new String(bytes, "UTF-8"); } else { logger.error("httpGet URL [" + url + "],httpEntity is null."); } return result; } } catch (Exception e) { logger.error("httpGet URL [" + url + "] error, ", e); return ""; } }
From source file:com.kkbox.toolkit.internal.api.APIRequest.java
private InputStream getInputStreamFromHttpResponse() throws IOException { InputStream inputStream;//w w w . j a va 2 s.co m Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) { byte[] inputStreamBuffer = new byte[8192]; int length; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); GZIPInputStream gZIPInputStream = new GZIPInputStream( new ByteArrayInputStream(EntityUtils.toByteArray(response.getEntity()))); while ((length = gZIPInputStream.read(inputStreamBuffer)) >= 0) { byteArrayOutputStream.write(inputStreamBuffer, 0, length); } inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); gZIPInputStream.close(); byteArrayOutputStream.close(); } else { inputStream = response.getEntity().getContent(); } return inputStream; }