List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:edu.tum.cs.ias.knowrob.BarcodeWebLookup.java
public static String lookUpEANsearch(String ean) { String res = ""; if (ean != null && ean.length() > 0) { HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); //httpclient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-16"); try {//w w w . ja va 2s . c o m HttpGet httpget = new HttpGet("http://www.ean-search.org/perl/ean-search.pl?ean=" + ean + "&os=1"); httpget.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8"); httpget.getParams().setParameter(CoreProtocolPNames.HTTP_ELEMENT_CHARSET, "ASCII"); System.out.println(httpget.getURI()); // Create a response handler 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[] response = httpclient.execute(httpget, handler); // String responseBody = httpclient.execute(httpget, handler); // new HeapByteBuffer(responseBody.getBytes(), 0, responseBody.getBytes().length)); // // Charset a = Charset.forName("UTF-8"); // a.newEncoder().encode(responseBody.getBytes()); // // System.out.println(responseBody); // Parse response document res = response.toString(); } catch (UnsupportedEncodingException uee) { uee.printStackTrace(); } catch (ClientProtocolException cpe) { cpe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } finally { if (httpclient != null) { httpclient.getConnectionManager().shutdown(); } } } return res; }
From source file:org.apache.commons.jcs.auxiliary.remote.http.client.RemoteHttpCacheDispatcher.java
/** * Process single request/* w w w . ja v a 2 s . co m*/ * * @param requestAsByteArray request body * @param remoteCacheRequest the cache request * @param url target url * * @return byte[] - the response * * @throws IOException * @throws HttpException */ protected <K, V> byte[] processRequest(byte[] requestAsByteArray, RemoteCacheRequest<K, V> remoteCacheRequest, String url) throws IOException, HttpException { RequestBuilder builder = RequestBuilder.post(url).setCharset(DEFAULT_ENCODING); if (getRemoteHttpCacheAttributes().isIncludeCacheNameAsParameter() && remoteCacheRequest.getCacheName() != null) { builder.addParameter(PARAMETER_CACHE_NAME, remoteCacheRequest.getCacheName()); } if (getRemoteHttpCacheAttributes().isIncludeKeysAndPatternsAsParameter()) { String keyValue = ""; switch (remoteCacheRequest.getRequestType()) { case GET: case REMOVE: case GET_KEYSET: keyValue = remoteCacheRequest.getKey().toString(); break; case GET_MATCHING: keyValue = remoteCacheRequest.getPattern(); break; case GET_MULTIPLE: keyValue = remoteCacheRequest.getKeySet().toString(); break; case UPDATE: keyValue = remoteCacheRequest.getCacheElement().getKey().toString(); break; default: break; } builder.addParameter(PARAMETER_KEY, keyValue); } if (getRemoteHttpCacheAttributes().isIncludeRequestTypeasAsParameter()) { builder.addParameter(PARAMETER_REQUEST_TYPE, remoteCacheRequest.getRequestType().toString()); } builder.setEntity(new ByteArrayEntity(requestAsByteArray)); HttpResponse httpResponse = doWebserviceCall(builder); byte[] response = EntityUtils.toByteArray(httpResponse.getEntity()); return response; }
From source file:com.caibowen.gplume.misc.test.HttpClientUtil.java
public static byte[] getBytes(String url, Map<String, String> params, int connectTimeout) { final String uri = setParam(url, params, Consts.UTF_8); final HttpGet get = new HttpGet(uri); get.setConfig(buildConfig(connectTimeout, connectTimeout)); try {/*from w w w . j a va2 s. c o m*/ final CloseableHttpResponse response = httpClient.execute(get); try { final HttpEntity entity = response.getEntity(); if (entity.getContentLength() > 0) return EntityUtils.toByteArray(entity); logger.error("[HttpUtils Get]get content error,content=" + EntityUtils.toString(entity)); } catch (Exception e) { logger.error(String.format("[HttpUtils Get]get response error, url:%s", uri), e); } finally { if (response != null) response.close(); } } catch (SocketTimeoutException e) { logger.error(String.format("[HttpUtils Get]invoke get timeout error, url:%s", uri), e); } catch (Exception e) { logger.error(String.format("[HttpUtils Get]invoke get error, url:%s", uri), e); } finally { get.releaseConnection(); } return null; }
From source file:com.mobileaffairs.seminar.videolib.VideoLibSyncAdapter.java
private byte[] readImage(String url) { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); try {//from w w w .jav a 2 s .c om HttpResponse response = client.execute(httpGet); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); byte[] imageBytes = EntityUtils.toByteArray(entity); return imageBytes; } else { Log.e("readImage", "Failed to download file"); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple GET requests *//*from w ww . j a v a 2 s . c om*/ @LargeTest public void testSimpleBasicHttpRequests() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data final List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(5000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String s = request.getRequestLine().getUri(); if (s.startsWith("/?")) { s = s.substring(2); } int index = Integer.parseInt(s); byte[] data = (byte[]) testData.get(index); ByteArrayEntity entity = new ByteArrayEntity(data); response.setEntity(entity); } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpRequest get = new BasicHttpRequest("GET", "/?" + r); HttpResponse response = this.client.execute(get, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
From source file:fr.ippon.wip.http.hc.HttpClientExecutor.java
/** * Send an HTTP request to the remote site and process the returned HTTP * response This method://from w w w. j av a2s . c om * <ul> * <li>creates an org.apache.http.HttpRequest</li> * <li>executes it using instances of HttpClient and HttpContext provides by * HttpClientResourceManager</li> * <li>converts the resulting org.apache.http.HttpResponse to a * fr.ippon.wip.http.Response</li> * </ul> * * @param request * Contains all the data needed to create an * org.apache.http.HttpRequest * @param portletRequest * Gives access to javax.portlet.PortletSession and windowID * @param portletResponse * Used to create PortletURL if instance of MimeResponse * @return The returned Response instance can reference an InputStream * linked to a connection from an HttpClient pool It necessary to * call either Response#dispose, Response#printResponseContent or * Response#sendResponse to release the underlying HTTP connection. * @throws IOException */ public Response execute(RequestBuilder request, PortletRequest portletRequest, PortletResponse portletResponse) throws IOException { if (WIPUtil.isDebugMode(portletRequest)) WIPLogging.INSTANCE.logTransform(request.getRequestedURL()); Response response = null; HttpResponse httpResponse = null; HttpEntity responseEntity = null; HttpClientResourceManager resourceManager = HttpClientResourceManager.getInstance(); try { // Get Apache HttpComponents resources from ResourceManager HttpClient client = resourceManager.getHttpClient(portletRequest); HttpContext context = resourceManager.initExecutionContext(portletRequest, portletResponse, request); HttpUriRequest httpRequest; httpRequest = request.buildHttpRequest(); // Execute the request try { httpResponse = client.execute(httpRequest, context); responseEntity = httpResponse.getEntity(); // the HttpEntity content may be set as non repeatable, meaning it can be read only once byte[] responseBody = (responseEntity == null) ? null : EntityUtils.toByteArray(responseEntity); manageAuthentification(portletRequest, context, httpResponse); // what if the request was redirected? how to catch the last URL? String actualUrl = getActualUrl(portletRequest, context, request, httpResponse); // Create Response object from HttpResponse response = createResponse(httpResponse, responseBody, actualUrl, portletResponse instanceof MimeResponse); StringBuffer buffer = new StringBuffer(); buffer.append(httpRequest.getMethod() + " " + request.getRequestedURL() + " " + httpResponse.getProtocolVersion() + "\" " + httpResponse.getStatusLine().getStatusCode()); buffer.append("\n"); for (Header header : httpResponse.getAllHeaders()) buffer.append(header.getName() + " : " + header.getValue() + "\n"); ACCESS_LOG.log(Level.INFO, buffer.toString()); // logging if enabled if (WIPUtil.isDebugMode(portletRequest) && responseBody != null && !response.isBinary()) WIPLogging.INSTANCE.logTransform(new String(responseBody) + "\n"); } catch (RuntimeException rte) { throw rte; } } catch (URISyntaxException e) { LOG.log(Level.WARNING, "ERROR while creating URI", e); } finally { if (httpResponse != null && responseEntity != null) EntityUtils.consume(responseEntity); resourceManager.releaseThreadResources(); } return response; }
From source file:net.sf.jaceko.mock.it.helper.request.HttpRequestSender.java
private MockResponse executeRequest(HttpRequestBase httpRequest, boolean binary) throws IOException { HttpResponse response = httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); ContentType contentType = ContentType.getOrDefault(entity); String body = null;/*from w ww.j av a 2 s. c om*/ byte[] binaryBody = null; if (entity != null) { if (binary) { binaryBody = EntityUtils.toByteArray(entity); } else { body = EntityUtils.toString(entity); } entity.getContent().close(); } Map<String, String> headers = new HashMap<String, String>(); Header[] allHeaders = response.getAllHeaders(); for (Header header : allHeaders) { headers.put(header.getName(), header.getValue()); } int responseCode = response.getStatusLine().getStatusCode(); return MockResponse.body(body).binaryBody(binaryBody).code(responseCode) .contentType(MediaType.valueOf(contentType.getMimeType())).headers(headers).build(); }
From source file:org.esigate.http.HttpResponseUtils.java
/** * Returns the response body as a string or the reason phrase if body is empty. * <p>/*from w w w . j av a 2 s . c om*/ * This methods is similar to EntityUtils#toString() internally, but uncompress the entity first if necessary. * <p> * This methods also holds an extension point, which can be used to guess the real encoding of the entity, if the * HTTP headers set a wrong encoding declaration. * * @since 3.0 * @since 4.1 - Event EventManager.EVENT_READ_ENTITY is fired when calling this method. * * @param httpResponse * @param eventManager * @return The body as string or the reason phrase if body was empty. * @throws HttpErrorPage */ public static String toString(HttpResponse httpResponse, EventManager eventManager) throws HttpErrorPage { HttpEntity httpEntity = httpResponse.getEntity(); String result; if (httpEntity == null) { result = httpResponse.getStatusLine().getReasonPhrase(); } else { // Unzip the stream if necessary Header contentEncoding = httpEntity.getContentEncoding(); if (contentEncoding != null) { String contentEncodingValue = contentEncoding.getValue(); if ("gzip".equalsIgnoreCase(contentEncodingValue) || "x-gzip".equalsIgnoreCase(contentEncodingValue)) { httpEntity = new GzipDecompressingEntity(httpEntity); } else if ("deflate".equalsIgnoreCase(contentEncodingValue)) { httpEntity = new DeflateDecompressingEntity(httpEntity); } else { throw new UnsupportedContentEncodingException( "Content-encoding \"" + contentEncoding + "\" is not supported"); } } try { byte[] rawEntityContent = EntityUtils.toByteArray(httpEntity); ContentType contentType = null; Charset charset = null; String mimeType = null; try { contentType = ContentType.getOrDefault(httpEntity); mimeType = contentType.getMimeType(); charset = contentType.getCharset(); } catch (UnsupportedCharsetException ex) { throw new UnsupportedEncodingException(ex.getMessage()); } // Use default charset is no valid information found from HTTP // headers if (charset == null) { charset = HTTP.DEF_CONTENT_CHARSET; } ReadEntityEvent event = new ReadEntityEvent(mimeType, charset, rawEntityContent); // Read using charset based on HTTP headers event.setEntityContent(new String(rawEntityContent, charset)); // Allow extensions to detect document encoding if (eventManager != null) { eventManager.fire(EventManager.EVENT_READ_ENTITY, event); } return event.getEntityContent(); } catch (IOException e) { throw new HttpErrorPage(HttpErrorPage.generateHttpResponse(e)); } } return removeSessionId(result, httpResponse); }
From source file:com.subgraph.vega.internal.http.requests.EngineHttpResponse.java
@Override public boolean lockResponseEntity() { final HttpEntity entity = rawResponse.getEntity(); if (entity == null) return false; try {//from w w w . ja v a 2s . co m final ByteArrayEntity newEntity = new ByteArrayEntity(EntityUtils.toByteArray(entity)); newEntity.setContentType(entity.getContentType()); newEntity.setContentEncoding(entity.getContentEncoding()); rawResponse.setEntity(newEntity); EntityUtils.consume(entity); return true; } catch (IOException e) { logger.warning("Error loading entity for " + getRequestUri().toString() + " : " + e.getMessage()); return false; } }
From source file:com.wallpaper.core.loopj.android.http.BinaryHttpResponseHandler.java
void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); Header[] contentTypeHeaders = response.getHeaders("Content-Type"); byte[] responseBody = null; if (contentTypeHeaders.length != 1) { // malformed/ambiguous HTTP Header, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "None, or more than one, Content-Type Header found!"), responseBody); return;/*from w w w .java 2 s . c o m*/ } Header contentTypeHeader = contentTypeHeaders[0]; boolean foundAllowedContentType = false; for (String anAllowedContentType : mAllowedContentTypes) { if (anAllowedContentType.equals(contentTypeHeader.getValue())) { foundAllowedContentType = true; } } if (!foundAllowedContentType) { // Content-Type not in allowed list, ABORT! sendFailureMessage(new HttpResponseException(status.getStatusCode(), "Content-Type not allowed!"), responseBody); return; } try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); } responseBody = EntityUtils.toByteArray(entity); } catch (IOException e) { sendFailureMessage(e, (byte[]) null); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody); } else { sendSuccessMessage(responseBody); } }