List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:org.elasticsearch.client.RequestConvertersTests.java
public void testMultiSearch() throws IOException { int numberOfSearchRequests = randomIntBetween(0, 32); MultiSearchRequest multiSearchRequest = new MultiSearchRequest(); for (int i = 0; i < numberOfSearchRequests; i++) { SearchRequest searchRequest = randomSearchRequest(() -> { // No need to return a very complex SearchSourceBuilder here, that is tested // elsewhere SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.from(randomInt(10)); searchSourceBuilder.size(randomIntBetween(20, 100)); return searchSourceBuilder; });// w ww. ja va 2s . co m // scroll is not supported in the current msearch api, so unset it: searchRequest.scroll((Scroll) null); // only expand_wildcards, ignore_unavailable and allow_no_indices can be // specified from msearch api, so unset other options: IndicesOptions randomlyGenerated = searchRequest.indicesOptions(); IndicesOptions msearchDefault = new MultiSearchRequest().indicesOptions(); searchRequest.indicesOptions(IndicesOptions.fromOptions(randomlyGenerated.ignoreUnavailable(), randomlyGenerated.allowNoIndices(), randomlyGenerated.expandWildcardsOpen(), randomlyGenerated.expandWildcardsClosed(), msearchDefault.allowAliasesToMultipleIndices(), msearchDefault.forbidClosedIndices(), msearchDefault.ignoreAliases())); multiSearchRequest.add(searchRequest); } Map<String, String> expectedParams = new HashMap<>(); expectedParams.put(RestSearchAction.TYPED_KEYS_PARAM, "true"); if (randomBoolean()) { multiSearchRequest.maxConcurrentSearchRequests(randomIntBetween(1, 8)); expectedParams.put("max_concurrent_searches", Integer.toString(multiSearchRequest.maxConcurrentSearchRequests())); } Request request = RequestConverters.multiSearch(multiSearchRequest); assertEquals("/_msearch", request.getEndpoint()); assertEquals(HttpPost.METHOD_NAME, request.getMethod()); assertEquals(expectedParams, request.getParameters()); List<SearchRequest> requests = new ArrayList<>(); CheckedBiConsumer<SearchRequest, XContentParser, IOException> consumer = (searchRequest, p) -> { SearchSourceBuilder searchSourceBuilder = SearchSourceBuilder.fromXContent(p, false); if (searchSourceBuilder.equals(new SearchSourceBuilder()) == false) { searchRequest.source(searchSourceBuilder); } requests.add(searchRequest); }; MultiSearchRequest.readMultiLineFormat(new BytesArray(EntityUtils.toByteArray(request.getEntity())), REQUEST_BODY_CONTENT_TYPE.xContent(), consumer, null, multiSearchRequest.indicesOptions(), null, null, null, xContentRegistry(), true); assertEquals(requests, multiSearchRequest.requests()); }
From source file:org.elasticsearch.client.RequestConvertersTests.java
private static void assertToXContentBody(ToXContent expectedBody, HttpEntity actualEntity) throws IOException { BytesReference expectedBytes = XContentHelper.toXContent(expectedBody, REQUEST_BODY_CONTENT_TYPE, false); assertEquals(XContentType.JSON.mediaTypeWithoutParameters(), actualEntity.getContentType().getValue()); assertEquals(expectedBytes, new BytesArray(EntityUtils.toByteArray(actualEntity))); }
From source file:com.yeahka.android.lepos.Device.java
public ResultModel sendDataToO2OServer(String url, byte[] data, Class classOfT) { try {/*from ww w.jav a2s.c o m*/ HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 60 * 1000); HttpConnectionParams.setSoTimeout(httpParameters, 60 * 1000); // HttpClient client = new DefaultHttpClient(httpParameters); HttpClient client = MyHttps.getNewHttpClient(httpParameters); MyLog.d(TAG, url); HttpPost post = null; post = new HttpPost(url); post.setEntity(new ByteArrayEntity(data)); if (!isWifiEnabled) { String strProxyHost = android.net.Proxy.getDefaultHost(); if (strProxyHost != null && strProxyHost.length() > 0) { int nPort = android.net.Proxy.getDefaultPort(); post.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, new HttpHost(strProxyHost, nPort)); } } HttpResponse response; response = client.execute(post); StringBuffer sb = new StringBuffer(); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200) { HttpEntity entity = response.getEntity(); // String strResult = EntityUtils.toString(entity); byte[] dataCache = EntityUtils.toByteArray(entity); byte[] bytesMsgHeader = new byte[4]; byte[] jsonBytes = null; System.arraycopy(dataCache, 0, bytesMsgHeader, 0, 4); if (!ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM, bytesMsgHeader)) { return new ResultModel(Device.SYSTEM_FAIL); } int length = dataCache.length - 4; bytesMsgHeader = new byte[length]; System.arraycopy(dataCache, 4, bytesMsgHeader, 0, length); for (int i = 0; i < length - 4; i++) { byte[] tempB = new byte[4]; System.arraycopy(bytesMsgHeader, i, tempB, 0, 4); if (ServerSocketConnectUtil.checkHead(ServerSocketConnectUtil.HEAD_REGISTER_SYSTEM_BODY_CONTENT, tempB)) { jsonBytes = new byte[length - i - 8]; System.arraycopy(bytesMsgHeader, i + 8, jsonBytes, 0, (length - i - 8)); // System.out.println("jsonBytes = " + jsonBytes.toString()); break; } } if (jsonBytes != null) { // System.out.println("jsonBytes ?? "); ResultModel resultModel = new ResultModel(jsonBytes, classOfT); return resultModel; } else { // System.out.println("jsonBytes ? "); return new ResultModel(Device.TRANSACTION_NET_FAIL); } } else { return new ResultModel(Device.TRANSACTION_NET_FAIL); } } catch (org.apache.http.conn.HttpHostConnectException ex) {// connect // exception return new ResultModel(Device.TRANSACTION_NET_FAIL, ex); } catch (java.net.SocketException ex) { return new ResultModel(Device.TRANSACTION_NET_FAIL, ex); } catch (java.net.SocketTimeoutException ex) { return new ResultModel(Device.TRANSACTION_NET_FAIL, ex); } catch (java.io.IOException ex) { return new ResultModel(Device.TRANSACTION_NET_FAIL, ex); } catch (Exception ex) { return new ResultModel(Device.TRANSACTION_NET_FAIL, ex); } }
From source file:org.eclipse.californium.proxy.HttpTranslator.java
/** * Method to map the http entity of a http message in a coherent payload for * the coap message. The method simply gets the bytes from the entity and, * if needed changes the charset of the obtained bytes to UTF-8. * /*from w w w . j av a2s .c o m*/ * @param httpEntity * the http entity * * @return byte[] * @throws TranslationException * the translation exception */ public static byte[] getCoapPayload(HttpEntity httpEntity) throws TranslationException { if (httpEntity == null) { throw new IllegalArgumentException("httpEntity == null"); } byte[] payload = null; try { // get the bytes from the entity payload = EntityUtils.toByteArray(httpEntity); if (payload != null && payload.length > 0 && looksLikeUTF8(payload)) { //modifica il payload per sostituire i riferimenti a http://proxyIP:8080/proxy/ String body = ""; try { body = new String(payload, "UTF-8"); } catch (UnsupportedEncodingException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } body = body.replace("http://" + proxyIP + ":8080/proxy/", "coap://"); payload = body.getBytes(); // the only supported charset in CoAP is UTF-8 Charset coapCharset = UTF_8; // get the charset for the http entity ContentType httpContentType = ContentType.getOrDefault(httpEntity); Charset httpCharset = httpContentType.getCharset(); // check if the charset is the one allowed by coap if (httpCharset != null && !httpCharset.equals(coapCharset)) { // translate the payload to the utf-8 charset payload = changeCharset(payload, httpCharset, coapCharset); } } else { int i = 0; } } catch (IOException e) { LOGGER.warning("Cannot get the content of the http entity: " + e.getMessage()); throw new TranslationException("Cannot get the content of the http entity", e); } finally { try { // ensure all content has been consumed, so that the // underlying connection could be re-used EntityUtils.consume(httpEntity); } catch (IOException e) { } } return payload; }
From source file:org.eclipse.skalli.core.rest.CompareAPIVersionsTest.java
private String getContent(HttpResponse resp) throws IOException { HttpEntity responseEntity = resp.getEntity(); if (responseEntity != null) { byte[] bytes = EntityUtils.toByteArray(responseEntity); return new String(bytes, "UTF-8"); }// w w w . ja va 2 s . c om return null; }
From source file:org.hydracache.server.httpd.handler.HttpPutMethodHandler.java
BlobDataMessage decodeProtocolMessage(HttpEntity entity) throws IOException { byte[] entityContent = EntityUtils.toByteArray(entity); if (log.isDebugEnabled()) { log.debug("Incoming entity content (bytes): " + entityContent.length); }/*from w w w. j av a 2 s . co m*/ DataMessage dataMessage = decoder.decode(Buffer.wrap(entityContent).asDataInputStream()); verifyMessageType(dataMessage); return (BlobDataMessage) dataMessage; }
From source file:org.jcodec.player.filters.http.Downloader.java
private List<Packet> extractFrame(byte[] bfr, HttpGet get) throws IOException, ClientProtocolException { get.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.IGNORE_COOKIES); HttpResponse response = privilegedExecute(client, get); HttpEntity entity = response.getEntity(); if (response.getStatusLine().getStatusCode() != 200) { if (entity != null) EntityUtils.toByteArray(entity); return null; }/*from w w w. j av a 2 s . com*/ Buffer buffer; if (bfr == null) buffer = new Buffer(EntityUtils.toByteArray(entity)); else { buffer = toBuffer(bfr, entity); } Header contentType = response.getLastHeader("Content-Type"); if (contentType != null && contentType.getValue().startsWith("multipart/mixed")) { List<Packet> result = parseMultipart(buffer, contentType.getValue()); return result.size() == 0 ? null : result; } else { return Arrays.asList(new Packet[] { pkt(toMap(response.getAllHeaders()), buffer) }); } }
From source file:org.kaaproject.kaa.client.transport.DesktopHttpClient.java
private byte[] getResponseBody(HttpResponse response, boolean verifyResponse) throws IOException, GeneralSecurityException { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { byte[] body = EntityUtils.toByteArray(resEntity); EntityUtils.consume(resEntity);//from w w w. ja v a 2 s.co m if (verifyResponse) { Header signatureHeader = response.getFirstHeader(CommonEpConstans.SIGNATURE_HEADER_NAME); if (signatureHeader == null) { throw new IOException("can't verify message"); } byte[] signature; if (signatureHeader.getValue() != null) { signature = Base64.decodeBase64(signatureHeader.getValue().getBytes(Charsets.UTF_8)); } else { signature = new byte[0]; } return verifyResponse(body, signature); } else { return body; } } else { throw new IOException("can't read message"); } }
From source file:org.ohmage.OhmageApi.java
private ImageReadResponse parseImageReadResponse(HttpResponse response) { Result result = Result.HTTP_ERROR; String[] errorCodes = null;// ww w. ja va 2 s . c o m ImageReadResponse candidate = new ImageReadResponse(); if (response != null) { Log.i(TAG, response.getStatusLine().toString()); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { try { if (responseEntity.getContentType().getValue().startsWith("image/")) { // it's the image data! result = Result.SUCCESS; // dealing with raw image data here. hmm. byte[] content = EntityUtils.toByteArray(responseEntity); candidate.setData(content); candidate.setType(responseEntity.getContentType().getValue()); } else { // it was a JSON error instead result = Result.FAILURE; try { JSONObject rootJson = new JSONObject(EntityUtils.toString(responseEntity)); JSONArray errorsJsonArray = rootJson.getJSONArray("errors"); int errorCount = errorsJsonArray.length(); errorCodes = new String[errorCount]; for (int i = 0; i < errorCount; i++) { errorCodes[i] = errorsJsonArray.getJSONObject(i).getString("code"); } } catch (JSONException e) { Log.e(TAG, "Problem parsing response json", e); result = Result.INTERNAL_ERROR; } } } catch (IOException e) { Log.e(TAG, "Problem reading response body", e); result = Result.INTERNAL_ERROR; } } else { Log.e(TAG, "No response entity in response"); result = Result.HTTP_ERROR; } } else { Log.e(TAG, "Returned status code: " + String.valueOf(response.getStatusLine().getStatusCode())); result = Result.HTTP_ERROR; } } else { Log.e(TAG, "Response is null"); result = Result.HTTP_ERROR; } candidate.setResponseStatus(result, errorCodes); return candidate; }
From source file:self.philbrown.droidQuery.AjaxTask.java
/** * Parses the HTTP response as a raw byte[] * @param response the response to parse * @return a byte[] response//ww w.j av a2s.com */ private byte[] parseRawContent(HttpResponse response) throws IOException { return EntityUtils.toByteArray(response.getEntity()); }