List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:ss.udapi.sdk.services.HttpServices.java
protected String retrieveBody(ServiceRequest request, String relation, String name, String entity) throws Exception { if (request == null) throw new IllegalArgumentException("request object cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); CloseableHttpClient httpClient = HttpClients.custom().setKeepAliveStrategy(requestTimeout).build(); Exception lastraisedexception = null; // Double check we do have an actual usable service RestItem serviceDetails = getRestItems(request, name); if (serviceDetails == null) { logger.error("No details found for: " + relation + " on " + name); return null; }/*from w w w .j a v a 2 s . com*/ // The retrieve that service's end-point RestLink link = getLink(serviceDetails, relation); if (link == null) { logger.error("No links found for: " + relation + " on " + name); return null; } String responseBody = ""; try { // Prepare the HTTP request depending on whether it's an echo // (POST), then send the request. if (relation.equals("http://api.sportingsolutions.com/rels/stream/batchecho")) { HttpPost httpPost = new HttpPost(link.getHref()); httpPost.setHeader("X-Auth-Token", request.getAuthToken()); httpPost.setHeader("Content-Type", "application/json"); if (compressionEnabled == true) { httpPost.setHeader("Accept-Encoding", "gzip"); } HttpEntity myEntity = new StringEntity(entity); httpPost.setEntity(myEntity); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); if (httpResponse.getStatusLine().getStatusCode() != 202) { throw new ClientProtocolException("Unexpected response status for echo request: " + httpResponse.getStatusLine().getStatusCode()); } HttpEntity responseEntity = httpResponse.getEntity(); if (responseEntity != null) { responseBody = new String(EntityUtils.toByteArray(responseEntity)); } // Or anything else (GET), then send the request. } else { HttpGet httpGet = new HttpGet(link.getHref()); httpGet.setHeader("X-Auth-Token", request.getAuthToken()); if (compressionEnabled == true) { httpGet.setHeader("Accept-Encoding", "gzip"); } logger.debug("Sending request for relation:[" + relation + "] name:[" + name + "] to href:[" + link.getHref() + "]"); ResponseHandler<String> responseHandler = getResponseHandler(200); responseBody = httpClient.execute(httpGet, responseHandler); } } catch (ClientProtocolException protEx) { logger.error("Invalid Client Protocol: " + protEx.getMessage() + " while processing : " + name); lastraisedexception = protEx; } catch (IOException ioEx) { logger.error("Communication error: " + ioEx.getMessage() + " while processing : " + name); lastraisedexception = ioEx; } finally { try { httpClient.close(); } catch (IOException ex) { // Can safely be ignored, either the server closed the // connection or we didn't open it so there's nothing to do } } if (lastraisedexception != null) throw lastraisedexception; // Then return the response we got from Sporting Solutions. return responseBody; }
From source file:eu.esdihumboldt.hale.io.wfs.AbstractWFSWriter.java
private Document parseResponse(HttpEntity entity) throws IOException, ParserConfigurationException, SAXException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); byte[] data = EntityUtils.toByteArray(entity); try (InputStream response = new ByteArrayInputStream(data)) { return builder.parse(response); } catch (SAXException e) { String response = new String(data, StandardCharsets.UTF_8); throw new SAXException("Invalid XML response: " + response, e); }/*from www . j a v a 2s .c o m*/ }
From source file:cn.wanghaomiao.seimi.core.SeimiProcessor.java
private Response renderResponse(HttpResponse httpResponse, Request request, HttpContext httpContext) { Response seimiResponse = new Response(); HttpEntity entity = httpResponse.getEntity(); seimiResponse.setHttpResponse(httpResponse); seimiResponse.setReponseEntity(entity); seimiResponse.setRealUrl(getRealUrl(httpContext)); seimiResponse.setUrl(request.getUrl()); seimiResponse.setRequest(request);/*from ww w . ja v a2s . c o m*/ seimiResponse.setMeta(request.getMeta()); if (entity != null) { Header referer = httpResponse.getFirstHeader("Referer"); if (referer != null) { seimiResponse.setReferer(referer.getValue()); } if (!entity.getContentType().getValue().contains("image")) { seimiResponse.setBodyType(BodyType.TEXT); try { seimiResponse.setData(EntityUtils.toByteArray(entity)); ContentType contentType = ContentType.get(entity); Charset charset = contentType.getCharset(); if (charset == null) { seimiResponse.setContent(new String(seimiResponse.getData(), "ISO-8859-1")); String docCharset = renderRealCharset(seimiResponse); seimiResponse.setContent( new String(seimiResponse.getContent().getBytes("ISO-8859-1"), docCharset)); seimiResponse.setCharset(docCharset); } else { seimiResponse.setContent(new String(seimiResponse.getData(), charset)); seimiResponse.setCharset(charset.name()); } } catch (Exception e) { e.printStackTrace(); logger.error("no content data"); } } else { seimiResponse.setBodyType(BodyType.BINARY); try { seimiResponse.setData(EntityUtils.toByteArray(entity)); seimiResponse.setContent(StringUtils.substringAfterLast(request.getUrl(), "/")); } catch (Exception e) { logger.error("no data can be read from httpResponse"); } } } return seimiResponse; }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests with chunk * coded content content. /*from w w w. j av a 2 s. co m*/ */ @LargeTest public void testSimpleHttpPostsChunked() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); 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 { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); 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()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, 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:org.fourthline.cling.transport.impl.apache.StreamClientImpl.java
protected ResponseHandler<StreamResponseMessage> createResponseHandler() { return new ResponseHandler<StreamResponseMessage>() { public StreamResponseMessage handleResponse(final HttpResponse httpResponse) throws IOException { StatusLine statusLine = httpResponse.getStatusLine(); if (log.isLoggable(Level.FINE)) log.fine("Received HTTP response: " + statusLine); // Status UpnpResponse responseOperation = new UpnpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase()); // Message StreamResponseMessage responseMessage = new StreamResponseMessage(responseOperation); // Headers responseMessage.setHeaders(new UpnpHeaders(HeaderUtil.get(httpResponse))); // Body HttpEntity entity = httpResponse.getEntity(); if (entity == null || entity.getContentLength() == 0) return responseMessage; if (responseMessage.isContentTypeMissingOrText()) { if (log.isLoggable(Level.FINE)) log.fine("HTTP response message contains text entity"); responseMessage.setBody(UpnpMessage.BodyType.STRING, EntityUtils.toString(entity)); } else { if (log.isLoggable(Level.FINE)) log.fine("HTTP response message contains binary entity"); responseMessage.setBody(UpnpMessage.BodyType.BYTES, EntityUtils.toByteArray(entity)); }/*from w ww. j av a2 s . co m*/ return responseMessage; } }; }
From source file:org.opensaml.util.http.HttpResource.java
/** * Saves the remote data to the backup file and returns an {@link InputStream} to the given data. Also updates the * cached resource ETag and last modified time as well as the charset used for the data. * //from ww w. j a v a 2 s. co m * @param response response from the HTTP request * * @return the resource data * * @throws ResourceException thrown if there is a problem saving the resource data to the backup file */ private InputStream getInputStreamFromResponse(final HttpResponse response) throws ResourceException { try { final byte[] responseEntity = EntityUtils.toByteArray(response.getEntity()); log.debug("Recived response entity of {} bytes", responseEntity.length); saveToBackupFile(responseEntity); cachedResourceETag = getETag(response); cachedResourceLastModified = getLastModified(response); log.debug("HTTP response included an ETag of {} and a Last-Modified of {}", cachedResourceETag, cachedResourceLastModified); return new ByteArrayInputStream(responseEntity); } catch (Exception e) { log.debug( "Error retrieving metadata from '{}' and saving backup copy to '{}'. Reading data from cached copy if available", resourceUrl, getBackupFilePath()); return getInputStreamFromBackupFile(); } }
From source file:org.perfcake.message.sender.HttpClientSender.java
@Override public Serializable doSend(final Message message, final MeasurementUnit measurementUnit) throws Exception { currentHttpResponse = httpClient.execute(currentRequest); final int respCode = currentHttpResponse.getStatusLine().getStatusCode(); if (!checkResponseCode(respCode)) { final StringBuilder errorMess = new StringBuilder(); errorMess.append("The server returned an unexpected HTTP response code: ").append(respCode).append(" ") .append("\"").append(currentHttpResponse.getStatusLine().getReasonPhrase()) .append("\". Expected HTTP codes are "); for (final int code : expectedResponseCodeList) { errorMess.append(Integer.toString(code)).append(", "); }/*from w ww . j a v a 2 s . c om*/ throw new PerfCakeException(errorMess.substring(0, errorMess.length() - 2) + "."); } return new String(EntityUtils.toByteArray(currentHttpResponse.getEntity()), Utils.getDefaultEncoding()); }
From source file:com.cellbots.httpserver.HttpCommandServer.java
public void handle(final HttpServerConnection conn, final HttpContext context) throws HttpException, IOException { HttpRequest request = conn.receiveRequestHeader(); HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_OK, "OK"); String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST") && !method.equals("PUT")) { throw new MethodNotSupportedException(method + " method not supported"); }/* w w w . j a v a2 s. c o m*/ // Get the requested target. This is the string after the domain name in // the URL. If the full URL was http://mydomain.com/test.html, target // will be /test.html. String target = request.getRequestLine().getUri(); //Log.w(TAG, "*** Request target: " + target); // Gets the requested resource name. For example, if the full URL was // http://mydomain.com/test.html?x=1&y=2, resource name will be // test.html final String resName = getResourceNameFromTarget(target); UrlParams params = new UrlParams(target); //Log.w(TAG, "*** Request LINE: " + request.getRequestLine().toString()); //Log.w(TAG, "*** Request resource: " + resName); if (method.equals("POST") || method.equals("PUT")) { byte[] entityContent = null; // Gets the content if the request has an entity. if (request instanceof HttpEntityEnclosingRequest) { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); if (entity != null) { entityContent = EntityUtils.toByteArray(entity); } } response.setStatusCode(HttpStatus.SC_OK); if (serverListener != null) { serverListener.onRequest(resName, params.keys, params.values, entityContent); } } else if (dataMap.containsKey(resName)) { // The requested resource is // a byte array response.setStatusCode(HttpStatus.SC_OK); response.setHeader("Content-Type", dataMap.get(resName).contentType); response.setEntity(new ByteArrayEntity(dataMap.get(resName).resource)); } else { // Resource is a file recognized by the app String fileName = resourceMap.containsKey(resName) ? resourceMap.get(resName).resource : resName; String contentType = resourceMap.containsKey(resName) ? resourceMap.get(resName).contentType : "text/html"; Log.d(TAG, "*** mapped resource: " + fileName); Log.d(TAG, "*** checking for file: " + rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); response.setStatusCode(HttpStatus.SC_OK); final File file = new File(rootDir + (rootDir.endsWith("/") ? "" : "/") + fileName); if (file.exists() && !file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); FileEntity body = new FileEntity(file, URLConnection.guessContentTypeFromName(fileName)); response.setHeader("Content-Type", URLConnection.guessContentTypeFromName(fileName)); response.setEntity(body); } else if (file.isDirectory()) { response.setStatusCode(HttpStatus.SC_OK); EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); ArrayList<String> fileList = getDirListing(file); String resp = "{ \"list\": ["; for (String fl : fileList) { resp += "\"" + fl + "\","; } resp = resp.substring(0, resp.length() - 1); resp += "]}"; writer.write(resp); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else if (resourceMap.containsKey(resName)) { EntityTemplate body = new EntityTemplate(new ContentProducer() { public void writeTo(final OutputStream outstream) throws IOException { OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8"); writer.write(resourceMap.get(resName).resource); writer.flush(); } }); body.setContentType(contentType); response.setEntity(body); } else { response.setStatusCode(HttpStatus.SC_NOT_FOUND); response.setEntity(new StringEntity("Not Found")); } } conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); conn.shutdown(); }
From source file:org.s1.testing.httpclient.TestHttpClient.java
/** * * @param u//from w w w .j a v a 2 s .co m * @param data * @param name * @param contentType * @return */ public HttpResponseBean uploadFile(String u, InputStream data, String name, String contentType) { Map<String, Object> headers = new HashMap<String, Object>(); u = getURL(u, null); HttpPost post = new HttpPost(u); try { MultipartEntity request = new MultipartEntity(); ContentBody body = new InputStreamBody(data, contentType, name); request.addPart("file", body); post.setEntity(request); for (String h : headers.keySet()) { post.setHeader(h, "" + headers.get(h)); } 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(); } }