List of usage examples for org.apache.http.util EntityUtils toByteArray
public static byte[] toByteArray(HttpEntity httpEntity) throws IOException
From source file:jfabrix101.lib.helper.NetworkHelper.java
/** * Download content from a URL in binary format with a max size. * //from w w w. j a va 2 s .c om * @param url - URL from which to download * @return - The array of byte of content * @throws Exception - Exception if something went wrong or the content-lngth is too long */ public static byte[] getBinaryData(String url, long maxSizeLength) throws Exception { HttpClient client = new DefaultHttpClient(); HttpGet getHttp = new HttpGet(url); HttpResponse response = client.execute(getHttp); int returnCode = response.getStatusLine().getStatusCode(); long length = response.getEntity().getContentLength(); if (length > maxSizeLength) throw new RuntimeException("contentLength too big !!"); byte[] result = EntityUtils.toByteArray(response.getEntity()); if (returnCode != HttpStatus.SC_OK) { mLogger.error("UpdateServiceHelper() - Network error reading URL %s", url); mLogger.error("UpdateServiceHelper() - Network error: HttpStatusCode : %s", response.getStatusLine().getStatusCode()); return null; } return result; }
From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java
@Override public HTTPResponse fetch(final HTTPRequest request) throws IOException { final HttpClient httpClient = new DefaultHttpClient(); final URL url = request.getURL(); final HTTPRequestMethod requestMethod = request.getRequestMethod(); HttpUriRequest httpUriRequest = null; try {/*from w w w . j a v a2s .c o m*/ final byte[] payload = request.getPayload(); switch (requestMethod) { case GET: final HttpGet httpGet = new HttpGet(url.toURI()); // FIXME: GET with payload httpUriRequest = httpGet; break; case DELETE: httpUriRequest = new HttpDelete(url.toURI()); break; case HEAD: httpUriRequest = new HttpHead(url.toURI()); break; case POST: final HttpPost httpPost = new HttpPost(url.toURI()); if (null != payload) { httpPost.setEntity(new ByteArrayEntity(payload)); } httpUriRequest = httpPost; break; case PUT: final HttpPut httpPut = new HttpPut(url.toURI()); if (null != payload) { httpPut.setEntity(new ByteArrayEntity(payload)); } httpUriRequest = httpPut; break; default: throw new RuntimeException("Unsupported HTTP request method[" + requestMethod.name() + "]"); } } catch (final Exception e) { LOGGER.log(Level.SEVERE, "URL fetch failed", e); throw new IOException("URL fetch failed [msg=" + e.getMessage() + ']'); } final List<HTTPHeader> headers = request.getHeaders(); for (final HTTPHeader header : headers) { httpUriRequest.addHeader(header.getName(), header.getValue()); } final HttpResponse res = httpClient.execute(httpUriRequest); final HTTPResponse ret = new HTTPResponse(); ret.setContent(EntityUtils.toByteArray(res.getEntity())); ret.setResponseCode(res.getStatusLine().getStatusCode()); return ret; }
From source file:com.alibaba.shared.django.DjangoClient.java
public byte[] downloadFile(String fileId) throws URISyntaxException, IOException { URI uri = new URIBuilder(downloadFileUrl).addParameter(ACCESS_TOKEN_KEY, accessToken()) .addParameter("fileIds", fileId).build(); HttpGet req = new HttpGet(uri); HttpResponse resp = getHttpClient().execute(req); if (resp.getStatusLine().getStatusCode() == 200) { return EntityUtils.toByteArray(resp.getEntity()); }// w w w . jav a2s. c o m return null; }
From source file:org.zalando.stups.tokens.CloseableHttpProvider.java
public AccessToken createToken(final AccessTokenConfiguration tokenConfig) throws UnsupportedEncodingException { final List<NameValuePair> values = buildParameterList(tokenConfig); final HttpPost request = new HttpPost(accessTokenUri); request.setEntity(new UrlEncodedFormEntity(values)); request.setConfig(requestConfig);// w w w . ja va 2s .c o m try (final CloseableHttpResponse response = client.execute(host, request, localContext)) { // success status code? final int status = response.getStatusLine().getStatusCode(); if (status < 200 || status >= 300) { throw AccessTokenEndpointException.from(response); } // get json response final HttpEntity entity = response.getEntity(); final AccessTokenResponse accessTokenResponse = OBJECT_MAPPER.readValue(EntityUtils.toByteArray(entity), AccessTokenResponse.class); // create new access token object final Date validUntil = new Date( System.currentTimeMillis() + (accessTokenResponse.getExpiresInSeconds() * 1000)); return new AccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getTokenType(), accessTokenResponse.getExpiresInSeconds(), validUntil); } catch (Throwable t) { throw new AccessTokenEndpointException(t.getMessage(), t); } }
From source file:org.openqa.selenium.remote.internal.ApacheHttpClient.java
private HttpResponse createResponse(org.apache.http.HttpResponse response, HttpContext context) throws IOException { HttpResponse internalResponse = new HttpResponse(); internalResponse.setStatus(response.getStatusLine().getStatusCode()); for (Header header : response.getAllHeaders()) { internalResponse.addHeader(header.getName(), header.getValue()); }//from w w w .j ava2 s .c om HttpEntity entity = response.getEntity(); if (entity != null) { try { internalResponse.setContent(EntityUtils.toByteArray(entity)); } finally { EntityUtils.consume(entity); } } Object host = context.getAttribute(HTTP_TARGET_HOST); if (host instanceof HttpHost) { internalResponse.setTargetHost(((HttpHost) host).toURI()); } return internalResponse; }
From source file:com.flipkart.aesop.serializer.batch.reader.UserInfoServiceScanReader.java
/** * Interface method implementation.Scans and retrieves a number of {@link UserInfo} instances looked up from a service end-point. The scan stops once no more * data is returned by the service endpoint. * Note : The end-point and parameters used here are very specific to this sample. Also the code is mostly for testing and production * ready (no Http connection pools etc.) * @see org.springframework.batch.item.ItemReader#read() *//* w w w .j av a 2 s . co m*/ public UserInfo read() throws Exception, UnexpectedInputException, ParseException { // return data from local queue if available already synchronized (this) { // include the check for empty and remove in one synchronized block to avoid race conditions if (!this.localQueue.isEmpty()) { LOGGER.debug("Returning data from local cache. Cache size : " + this.localQueue.size()); return this.localQueue.poll(); } } parallelFetch.acquire(); int startIndex = 0; synchronized (this) { startIndex = resultCount += BATCH_SIZE; } if (this.resultCount < MAX_RESULTS) { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet executionGet = new HttpGet(BATCH_SERVICE_URL); URIBuilder uriBuilder = new URIBuilder(executionGet.getURI()); uriBuilder.addParameter("start", String.valueOf(startIndex)); uriBuilder.addParameter("count", String.valueOf(BATCH_SIZE)); ((HttpRequestBase) executionGet).setURI(uriBuilder.build()); HttpResponse httpResponse = httpclient.execute(executionGet); String response = new String(EntityUtils.toByteArray(httpResponse.getEntity())); ScanResult scanResult = objectMapper.readValue(response, ScanResult.class); if (scanResult.getCount() <= 0) { parallelFetch.release(); return null; } LOGGER.info("Fetched User Info objects in range - Start : {}. Count : {}", startIndex, scanResult.getCount()); for (UserInfo userInfo : scanResult.getResponse()) { this.localQueue.add(userInfo); } } parallelFetch.release(); return this.localQueue.poll(); }
From source file:org.aerogear.android.impl.core.HttpRestProvider.java
private HeaderAndBody execute(HttpRequestBase method) throws IOException { method.setHeader("Accept", "application/json"); method.setHeader("Content-type", "application/json"); for (Entry<String, String> entry : defaultHeaders.entrySet()) { method.setHeader(entry.getKey(), entry.getValue()); }/*from w ww. j a v a 2s. com*/ HttpResponse response = client.execute(method); int statusCode = response.getStatusLine().getStatusCode(); byte[] data = EntityUtils.toByteArray(response.getEntity()); response.getEntity().consumeContent(); if (statusCode != 200) { throw new HttpException(data, statusCode); } Header[] headers = response.getAllHeaders(); HeaderAndBody result = new HeaderAndBody(data, new HashMap<String, Object>(headers.length)); for (Header header : headers) { result.setHeader(header.getName(), header.getValue()); } return result; }
From source file:DeliverWork.java
private static String saveIntoWeed(RemoteFile remoteFile, String projectId) throws SQLException, UnsupportedEncodingException { String url = "http://59.215.226.174/WebDiskServerDemo/doc?doc_id=" + URLEncoder.encode(remoteFile.getFileId(), "utf-8"); CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; String res = ""; try {// w ww .jav a2s . c o m httpClient = HttpClients.createSystem(); // http(get?) HttpGet httpget = new HttpGet(url); response = httpClient.execute(httpget); HttpEntity result = response.getEntity(); String fileName = remoteFile.getFileName(); FileHandleStatus fileHandleStatus = getFileTemplate().saveFileByStream(fileName, new ByteArrayInputStream(EntityUtils.toByteArray(result))); System.out.println(fileHandleStatus); File file = new File(); if (result != null && result.getContentType() != null && result.getContentType().getValue() != null) { file.setContentType(result.getContentType().getValue()); } else { file.setContentType("application/error"); } file.setDataId(Integer.parseInt(projectId)); file.setName(fileName); if (fileName.contains(".bmp") || fileName.contains(".jpg") || fileName.contains(".jpeg") || fileName.contains(".png") || fileName.contains(".gif")) { file.setType(1); } else if (fileName.contains(".doc") || fileName.contains(".docx")) { file.setType(2); } else if (fileName.contains(".xlsx") || fileName.contains("xls")) { file.setType(3); } else if (fileName.contains(".pdf")) { file.setType(4); } else { file.setType(5); } String accessUrl = "/" + fileHandleStatus.getFileId().replaceAll(",", "/").concat("/").concat(fileName); file.setUrl(accessUrl); file.setSize(fileHandleStatus.getSize()); file.setPostTime(new java.util.Date()); file.setStatus(0); file.setEnumValue(findFileType(remoteFile.getFileType())); file.setResources(1); // JdbcFactory jdbcFactoryChanye=new JdbcFactory("jdbc:mysql://127.0.0.1:3306/fp_guimin?useUnicode=true&characterEncoding=UTF-8","root","111111","com.mysql.jdbc.Driver"); // Connection connection = jdbcFactoryChanye.getConnection(); DatabaseMetaData dmd = connection.getMetaData(); PreparedStatement ps = connection.prepareStatement(insertFile, new String[] { "ID" }); ps.setString(1, sdf.format(file.getPostTime())); ps.setInt(2, file.getType()); ps.setString(3, file.getEnumValue()); ps.setInt(4, file.getDataId()); ps.setString(5, file.getUrl()); ps.setString(6, file.getName()); ps.setString(7, file.getContentType()); ps.setLong(8, file.getSize()); ps.setInt(9, file.getStatus()); ps.setInt(10, file.getResources()); ps.executeUpdate(); if (dmd.supportsGetGeneratedKeys()) { ResultSet rs = ps.getGeneratedKeys(); while (rs.next()) { System.out.println(rs.getLong(1)); } } ps.close(); res = "success"; } catch (ClientProtocolException e) { e.printStackTrace(); res = e.getMessage(); } catch (IOException e) { e.printStackTrace(); res = e.getMessage(); } catch (Exception ex) { ex.printStackTrace(); } finally { if (httpClient != null) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } if (response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } return res; }
From source file:com.onesite.commons.net.http.rest.client.RestClient.java
/** * Process the http response and set the status, message and result for the HttpResponse * /* w w w .j a v a 2 s. com*/ * @param response * @throws Exception */ private void processHttpResponse(HttpResponse response) throws Exception { status = response.getStatusLine().getStatusCode(); statusMessage = response.getStatusLine().getReasonPhrase(); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new Exception("Error: " + response.getStatusLine().getStatusCode()); } this.result = new String(EntityUtils.toByteArray(response.getEntity())); }