List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:com.DGSD.DGUtils.ImageDownloader.ImageLoader.java
protected byte[] retrieveImageData() throws IOException { HttpGet request = new HttpGet(imageUrl); HttpResponse response = httpClient.execute(request); return EntityUtils.toByteArray(response.getEntity()); }
From source file:it.anyplace.sync.httprelay.client.HttpRelayConnection.java
private HttpRelayProtos.HttpRelayServerMessage sendMessage( HttpRelayProtos.HttpRelayPeerMessage.Builder peerMessageBuilder) { try {// w w w . java 2 s . c o m if (!Strings.isNullOrEmpty(sessionId)) { peerMessageBuilder.setSessionId(sessionId); } logger.debug("send http relay peer message = {} session id = {} sequence = {}", peerMessageBuilder.getMessageType(), peerMessageBuilder.getSessionId(), peerMessageBuilder.getSequence()); HttpClient httpClient = HttpClients.custom() // .setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)) .build(); HttpPost httpPost = new HttpPost(httpRelayServerUrl); httpPost.setEntity(new ByteArrayEntity(peerMessageBuilder.build().toByteArray())); final HttpRelayProtos.HttpRelayServerMessage serverMessage = httpClient.execute(httpPost, new ResponseHandler<HttpRelayProtos.HttpRelayServerMessage>() { @Override public HttpRelayProtos.HttpRelayServerMessage handleResponse(HttpResponse response) throws ClientProtocolException, IOException { checkArgument(equal(response.getStatusLine().getStatusCode(), HttpStatus.SC_OK), "http error %s", response.getStatusLine()); return HttpRelayProtos.HttpRelayServerMessage .parseFrom(EntityUtils.toByteArray(response.getEntity())); } }); logger.debug("received http relay server message = {}", serverMessage.getMessageType()); checkArgument(!equal(serverMessage.getMessageType(), HttpRelayProtos.HttpRelayServerMessageType.ERROR), "server error : %s", new Object() { @Override public String toString() { return serverMessage.getData().toStringUtf8(); } }); return serverMessage; } catch (IOException ex) { throw new RuntimeException(ex); } }
From source file:org.infinispan.server.test.configs.ExampleConfigsTest.java
@Test @WithRunningServer("standalone-compatibility-mode") public void testCompatibilityModeConfig() throws Exception { MemcachedClient memcachedClient = null; CloseableHttpClient restClient = null; try {/*from ww w .j ava2s. co m*/ RemoteInfinispanMBeans s1 = createRemotes("standalone-compatibility-mode", "local", DEFAULT_CACHE_NAME); RemoteCache<Object, Object> s1Cache = createCache(s1); restClient = HttpClients.createDefault(); String restUrl = "http://" + s1.server.getHotrodEndpoint().getInetAddress().getHostName() + ":8080" + s1.server.getRESTEndpoint().getContextPath() + "/" + DEFAULT_CACHE_NAME; memcachedClient = new MemcachedClient(s1.server.getMemcachedEndpoint().getInetAddress().getHostName(), s1.server.getMemcachedEndpoint().getPort()); String key = "1"; // 1. Put with Hot Rod assertEquals(null, s1Cache.withFlags(Flag.FORCE_RETURN_VALUE).put(key, "v1".getBytes())); assertArrayEquals("v1".getBytes(), (byte[]) s1Cache.get(key)); // 2. Get with REST HttpGet get = new HttpGet(restUrl + "/" + key); HttpResponse getResponse = restClient.execute(get); assertEquals(HttpServletResponse.SC_OK, getResponse.getStatusLine().getStatusCode()); assertArrayEquals("v1".getBytes(), EntityUtils.toByteArray(getResponse.getEntity())); // 3. Get with Memcached assertArrayEquals("v1".getBytes(), readWithMemcachedAndDeserialize(key, memcachedClient)); key = "2"; // 1. Put with REST HttpPut put = new HttpPut(restUrl + "/" + key); put.setEntity(new ByteArrayEntity("<hey>ho</hey>".getBytes(), ContentType.APPLICATION_OCTET_STREAM)); HttpResponse putResponse = restClient.execute(put); assertEquals(HttpServletResponse.SC_OK, putResponse.getStatusLine().getStatusCode()); // 2. Get with Hot Rod assertArrayEquals("<hey>ho</hey>".getBytes(), (byte[]) s1Cache.get(key)); // 3. Get with Memcached assertArrayEquals("<hey>ho</hey>".getBytes(), readWithMemcachedAndDeserialize(key, memcachedClient)); } finally { if (restClient != null) { restClient.close(); } if (memcachedClient != null) { memcachedClient.close(); } } }
From source file:com.flipkart.poseidon.handlers.http.impl.SinglePoolHttpTaskHandler.java
/** * Helper method that converts Http response Body into a string. *///from w w w . jav a2 s. c o m private byte[] getResponseBody(HttpResponse response) throws Exception { if (response.getEntity() != null) { return EntityUtils.toByteArray(response.getEntity()); } return "".getBytes(); }
From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java
private Response createResponse(HttpResponse httpResponse, HttpContext context) throws IOException { org.openqa.selenium.remote.http.HttpResponse internalResponse = new org.openqa.selenium.remote.http.HttpResponse(); internalResponse.setStatus(httpResponse.getStatusLine().getStatusCode()); for (Header header : httpResponse.getAllHeaders()) { for (HeaderElement headerElement : header.getElements()) { internalResponse.addHeader(header.getName(), headerElement.getValue()); }/*from ww w.j a v a 2 s . co m*/ } HttpEntity entity = httpResponse.getEntity(); if (entity != null) { try { internalResponse.setContent(EntityUtils.toByteArray(entity)); } finally { EntityUtils.consume(entity); } } Response response = responseCodec.decode(internalResponse); if (response.getSessionId() == null) { HttpHost finalHost = (HttpHost) context.getAttribute(HttpCoreContext.HTTP_TARGET_HOST); String uri = finalHost.toURI(); String sessionId = HttpSessionId.getSessionId(uri); response.setSessionId(sessionId); } return response; }
From source file:com.oneguy.recognize.engine.GoogleStreamingEngine.java
byte[] getHttpData(String url) { String TAG = "getHttpData"; HttpGet httpGet = new HttpGet(url); byte[] result = null; try {/* ww w .j a v a 2 s .co m*/ HttpClient client = new DefaultHttpClient(); client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, TIMEOUT); client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, TIMEOUT); Log.d(TAG, "HTTP GET:" + httpGet.getURI() + " method:" + httpGet.getMethod()); HttpResponse httpResponse = client.execute(httpGet); if (httpResponse.getStatusLine().getStatusCode() == 200) { result = EntityUtils.toByteArray(httpResponse.getEntity()); Log.d(TAG, new String(result)); StreamResponse response = new StreamResponse(null, Status.SUCCESS); response.setResponse(result); response.setResponseCode(httpResponse.getStatusLine().getStatusCode()); Message msg = new Message(); msg.what = EVENT_RESPONSE; msg.obj = response; mHandler.sendMessage(msg); } } catch (ClientProtocolException e) { onError(e); e.printStackTrace(); } catch (IOException e) { onError(e); e.printStackTrace(); } return result; }
From source file:org.votingsystem.util.HttpHelper.java
public ResponseVS getData(String serverURL, ContentTypeVS contentType) { log.info("getData - contentType: " + contentType + " - serverURL: " + serverURL); ResponseVS responseVS = null;/*from ww w.j a v a2 s.c o m*/ CloseableHttpResponse response = null; HttpGet httpget = null; ContentTypeVS responseContentType = null; try { httpget = new HttpGet(serverURL); if (contentType != null) httpget.setHeader("Content-Type", contentType.getName()); response = httpClient.execute(httpget); log.info("----------------------------------------"); /*Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { System.out.println(headers[i]); }*/ log.info(response.getStatusLine().toString() + " - connManager stats: " + connManager.getTotalStats().toString()); log.info("----------------------------------------"); Header header = response.getFirstHeader("Content-Type"); if (header != null) responseContentType = ContentTypeVS.getByName(header.getValue()); if (ResponseVS.SC_OK == response.getStatusLine().getStatusCode()) { byte[] responseBytes = EntityUtils.toByteArray(response.getEntity()); responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes, responseContentType); } else { responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), EntityUtils.toString(response.getEntity()), responseContentType); } } catch (Exception ex) { log.log(Level.SEVERE, ex.getMessage(), ex); responseVS = new ResponseVS(ResponseVS.SC_ERROR, ContextVS.getInstance().getMessage("hostConnectionErrorMsg", serverURL)); if (httpget != null) httpget.abort(); } finally { try { if (response != null) response.close(); } catch (Exception ex) { log.log(Level.SEVERE, ex.getMessage(), ex); } return responseVS; } }
From source file:cm.aptoide.pt.RemoteInTab.java
private void downloadExtras(String srv) { String url = srv + REMOTE_EXTRAS_FILE; try {//from w w w.ja v a 2 s . c o m FileOutputStream saveit = new FileOutputStream(LOCAL_PATH + REMOTE_EXTRAS_FILE); HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, 5000); HttpConnectionParams.setSoTimeout(httpParameters, 5000); DefaultHttpClient mHttpClient = new DefaultHttpClient(httpParameters); HttpGet mHttpGet = new HttpGet(url); String[] logins = null; logins = db.getLogin(srv); if (logins != null) { URL mUrl = new URL(url); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(logins[0], logins[1])); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse.getStatusLine().getStatusCode() == 401) { /*Message msg = new Message(); msg.obj = new String(srv); secure_error_handler.sendMessage(msg);*/ } else { byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity()); saveit.write(buffer); } } catch (UnknownHostException e) { } catch (ClientProtocolException e) { } catch (IOException e) { } }
From source file:cm.aptoide.pt.RssHandler.java
private void getIcon(String uri, String name) { String url = mserver + "/" + uri; String file = mctx.getString(R.string.icons_path) + name; /*File exists = new File(file); if(exists.exists()){/* w w w. j a va 2 s.c om*/ return; }*/ try { FileOutputStream saveit = new FileOutputStream(file); DefaultHttpClient mHttpClient = new DefaultHttpClient(); HttpGet mHttpGet = new HttpGet(url); if (requireLogin) { URL mUrl = new URL(url); mHttpClient.getCredentialsProvider().setCredentials(new AuthScope(mUrl.getHost(), mUrl.getPort()), new UsernamePasswordCredentials(usern, passwd)); } HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet); if (mHttpResponse.getStatusLine().getStatusCode() == 401) { return; } else if (mHttpResponse.getStatusLine().getStatusCode() == 403) { return; } else { byte[] buffer = EntityUtils.toByteArray(mHttpResponse.getEntity()); saveit.write(buffer); } } catch (IOException e) { } catch (IllegalArgumentException e) { } }
From source file:com.dnanexus.DXHTTPRequest.java
/** * Issues a request against the specified resource and returns either the text of the response * or the parsed JSON of the response (depending on whether parseResponse is set). * * @throws DXAPIException If the server returns a complete response with an HTTP status code * other than 200 (OK).//from w ww . ja va 2s. c o m * @throws DXHTTPException If an error occurs while making the HTTP request or obtaining the * response (includes HTTP protocol errors). * @throws InternalError If the server returns an HTTP status code 500 and the environment * specifies that retries are disabled. * @throws ServiceUnavailableException If the server returns an HTTP status code 503 and * indicates that the client should retry the request at a later time, and the * environment specifies that retries are disabled. */ private ParsedResponse requestImpl(String resource, String data, boolean parseResponse, RetryStrategy retryStrategy) { HttpPost request = new HttpPost(apiserver + resource); if (securityContext == null || securityContext.isNull()) { throw new DXHTTPException(new IOException("No security context was set")); } request.setHeader("Content-Type", "application/json"); request.setHeader("Connection", "close"); request.setHeader("Authorization", securityContext.get("auth_token_type").textValue() + " " + securityContext.get("auth_token").textValue()); request.setEntity(new StringEntity(data, Charset.forName("UTF-8"))); // Retry with exponential backoff int timeoutSeconds = 1; int attempts = 0; while (true) { Integer statusCode = null; String requestId = ""; // This guarantees that we get at least one iteration around this loop before running // out of retries, so we can check at the bottom of the loop instead of the top. assert NUM_RETRIES > 0; // By default, our conservative strategy is to retry if the route permits it. Later we // may update this to unconditionally retry if we can definitely determine that the // server never saw the request. boolean retryRequest = (retryStrategy == RetryStrategy.SAFE_TO_RETRY); int retryAfterSeconds = 60; try { // In this block, any IOException will cause the request to be retried (up to a // total of NUM_RETRIES retries). RuntimeException (including DXAPIException) // instances are not caught and will immediately return control to the caller. // TODO: distinguish between errors during connection init and socket errors while // sending or receiving data. The former can always be retried, but the latter can // only be retried if the request is idempotent. HttpResponse response = httpclient.execute(request); statusCode = response.getStatusLine().getStatusCode(); requestId = getHeader(response, "X-Request-ID"); HttpEntity entity = response.getEntity(); if (statusCode == null) { throw new DXHTTPException(); } else if (statusCode == HttpStatus.SC_OK) { // 200 OK byte[] value = EntityUtils.toByteArray(entity); int realLength = value.length; if (entity.getContentLength() >= 0 && realLength != entity.getContentLength()) { // Content length mismatch. Retry is possible (if the route permits it). throw new IOException("Received response of " + realLength + " bytes but Content-Length was " + entity.getContentLength()); } else if (parseResponse) { JsonNode responseJson = null; try { responseJson = DXJSON.parseJson(new String(value, "UTF-8")); } catch (JsonProcessingException e) { if (entity.getContentLength() < 0) { // content-length was not provided, and the JSON could not be // parsed. Retry (if the route permits it) since this is probably // just a streaming request that encountered a transient error. throw new IOException( "Content-length was not provided and the response JSON could not be parsed."); } // This is probably a real problem (the request // is complete but doesn't parse), so avoid // masking it as an IOException (which is // rethrown as DXHTTPException below). If it // comes up frequently we can revisit how these // should be handled. throw new RuntimeException("Request is of the correct length but is unparseable", e); } catch (IOException e) { // TODO: characterize what kinds of errors // DXJSON.parseJson can emit, determine how we can // get here and what to do about it. throw new RuntimeException(e); } return new ParsedResponse(null, responseJson); } else { return new ParsedResponse(new String(value, Charset.forName("UTF-8")), null); } } else if (statusCode < 500) { // 4xx errors should be considered not recoverable. String responseStr = EntityUtils.toString(entity); String errorType = null; String errorMessage = responseStr; try { JsonNode responseJson = DXJSON.parseJson(responseStr); JsonNode errorField = responseJson.get("error"); if (errorField != null) { JsonNode typeField = errorField.get("type"); if (typeField != null) { errorType = typeField.asText(); } JsonNode messageField = errorField.get("message"); if (messageField != null) { errorMessage = messageField.asText(); } } } catch (IOException e) { // Just fall back to reproducing the entire response // body. } logError(errorType + ": " + errorMessage + ". Code: " + Integer.toString(statusCode) + " Request ID: " + requestId); throw DXAPIException.getInstance(errorType, errorMessage, statusCode); } else { // Propagate 500 error to caller if (this.disableRetry && statusCode != 503) { logError("POST " + resource + ": " + statusCode + " Internal Server Error, try " + String.valueOf(attempts + 1) + "/" + NUM_RETRIES + " Request ID: " + requestId); throw new InternalErrorException("Internal Server Error", statusCode); } // If retries enabled, 500 InternalError should get retried unconditionally retryRequest = true; if (statusCode == 503) { Header retryAfterHeader = response.getFirstHeader("retry-after"); // Consume the response to avoid leaking resources EntityUtils.consume(entity); if (retryAfterHeader != null) { try { retryAfterSeconds = Integer.parseInt(retryAfterHeader.getValue()); } catch (NumberFormatException e) { // Just fall back to the default } } throw new ServiceUnavailableException("503 Service Unavailable", statusCode, retryAfterSeconds); } throw new IOException(EntityUtils.toString(entity)); } } catch (ServiceUnavailableException e) { int secondsToWait = retryAfterSeconds; if (this.disableRetry) { logError("POST " + resource + ": 503 Service Unavailable, suggested wait " + secondsToWait + " seconds" + ". Request ID: " + requestId); throw e; } // Retries due to 503 Service Unavailable and Retry-After do NOT count against the // allowed number of retries. logError("POST " + resource + ": 503 Service Unavailable, waiting for " + Integer.toString(secondsToWait) + " seconds" + " Request ID: " + requestId); sleep(secondsToWait); continue; } catch (IOException e) { // Note, this catches both exceptions directly thrown from httpclient.execute (e.g. // no connectivity to server) and exceptions thrown by our code above after parsing // the response. logError(errorMessage("POST", resource, e.toString(), timeoutSeconds, attempts + 1, NUM_RETRIES)); if (attempts == NUM_RETRIES || !retryRequest) { if (statusCode == null) { throw new DXHTTPException(); } throw new InternalErrorException("Maximum number of retries reached, or unsafe to retry", statusCode); } } assert attempts < NUM_RETRIES; assert retryRequest; attempts++; // The number of failed attempts is now no more than NUM_RETRIES, and the total number // of attempts allowed is NUM_RETRIES + 1 (the first attempt, plus up to NUM_RETRIES // retries). So there is at least one more retry left; sleep before we retry. assert attempts <= NUM_RETRIES; sleep(timeoutSeconds); timeoutSeconds *= 2; } }