List of usage examples for org.apache.http.entity BufferedHttpEntity BufferedHttpEntity
public BufferedHttpEntity(HttpEntity httpEntity) throws IOException
From source file:io.vertx.tempmail.impl.TempMailClientImpl.java
private void doGenericRequest(String url, Handler<AsyncResult<JsonObject>> handler) { vertx.executeBlocking(future -> { HttpGet httpGet = new HttpGet(url); if (options.getProxy() != null) { RequestConfig response = RequestConfig.custom().setProxy(options.getProxy()).build(); httpGet.setConfig(response); }// w ww .j a v a 2 s. c o m try { CloseableHttpResponse response = httpclient.execute(httpGet); if (response.getStatusLine().getStatusCode() == 200) { HttpEntity ht = response.getEntity(); BufferedHttpEntity buf = new BufferedHttpEntity(ht); String responseContent = EntityUtils.toString(buf, "UTF-8"); JsonArray jsonArray = new JsonArray(responseContent); JsonObject jsonObject = new JsonObject(); jsonObject.put("result", jsonArray); future.complete(jsonObject); } } catch (Exception e) { log.warn(e, e); future.fail(e); } }, res -> { handler.handle(new AsyncResult<JsonObject>() { @Override public JsonObject result() { return res.succeeded() ? (JsonObject) res.result() : null; } @Override public Throwable cause() { return res.succeeded() ? null : res.cause(); } @Override public boolean succeeded() { return res.succeeded(); } @Override public boolean failed() { return res.failed(); } }); }); }
From source file:semanticweb.hws14.movapp.activities.MovieDetail.java
private void setData(final MovieDet movie) { Thread picThread = new Thread(new Runnable() { public void run() { try { ImageView img = (ImageView) findViewById(R.id.imageViewMovie); URL url = new URL(movie.getPoster()); HttpGet httpRequest;//from w w w . jav a 2 s . com httpRequest = new HttpGet(url.toURI()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpRequest); HttpEntity entity = response.getEntity(); BufferedHttpEntity b_entity = new BufferedHttpEntity(entity); InputStream input = b_entity.getContent(); Bitmap bitmap = BitmapFactory.decodeStream(input); img.setImageBitmap(bitmap); } catch (Exception ex) { Log.d("MovieDetail Picture Error ", ex.toString()); } } }); picThread.start(); if (!"".equals(movie.getTitle())) { TextView movieTitle = (TextView) findViewById(R.id.tvMovieTitle); movieTitle.setText(movie.getTitle()); movieTitle.setVisibility(View.VISIBLE); } if (!"".equals(movie.getPlot())) { TextView moviePlot = (TextView) findViewById(R.id.tvPlot); moviePlot.setText(movie.getPlot()); moviePlot.setVisibility(View.VISIBLE); } TextView ageRestriction = (TextView) findViewById(R.id.tvAgeRestriction); TextView arHc = (TextView) findViewById(R.id.tvAgeRestrictionHC); String aR = String.valueOf(movie.getRated()); //Decode the ageRestriction if (!aR.equals("")) { ageRestriction.setVisibility(View.VISIBLE); arHc.setVisibility(View.VISIBLE); if (aR.equals("X")) { ageRestriction.setText("18+"); } else if (aR.equals("R")) { ageRestriction.setText("16+"); } else if (aR.equals("M")) { ageRestriction.setText("12+"); } else if (aR.equals("G")) { ageRestriction.setText("6+"); } else { ageRestriction.setVisibility(View.GONE); arHc.setVisibility(View.GONE); } } TextView ratingCount = (TextView) findViewById(R.id.tvMovieRatingCount); TextView ratingCountHc = (TextView) findViewById(R.id.tvMovieRatingCountHC); String ratingCountText = movie.getVoteCount(); ratingCount.setText(ratingCountText); manageEmptyTextfields(ratingCountHc, ratingCount, ratingCountText, false); if (!"".equals(movie.getImdbRating())) { TextView movieRating = (TextView) findViewById(R.id.tvMovieRating); if (movie.getImdbRating().equals("0 No Rating")) { movieRating.setText("No Rating"); } else if (movie.getImdbRating().equals("0 No Data")) { movieRating.setText(""); } else { movieRating.setText(movie.getImdbRating() + "/10"); } movieRating.setVisibility(View.VISIBLE); findViewById(R.id.tvMovieRatingHC).setVisibility(View.VISIBLE); } TextView metaScore = (TextView) findViewById(R.id.tvMetaScore); TextView metaScoreHc = (TextView) findViewById(R.id.tvMetaScoreHC); String metaSoreText = String.valueOf(movie.getMetaScore()); metaScore.setText(metaSoreText + "/100"); manageEmptyTextfields(metaScoreHc, metaScore, metaSoreText, false); TextView tvGenreHc = (TextView) findViewById(R.id.tvGenreHC); TextView genre = (TextView) findViewById(R.id.tvGenre); String genreText = String.valueOf(movie.createTvOutOfList(movie.getGenres())); genre.setText(genreText); manageEmptyTextfields(tvGenreHc, genre, genreText, true); TextView releaseYear = (TextView) findViewById(R.id.tvReleaseYear); TextView releaseYearHc = (TextView) findViewById(R.id.tvReleaseYearHC); String releaseYearText = String.valueOf(movie.getReleaseYear()); releaseYear.setText(releaseYearText); manageEmptyTextfields(releaseYearHc, releaseYear, releaseYearText, true); TextView runtime = (TextView) findViewById(R.id.tvRuntime); TextView runTimeHc = (TextView) findViewById(R.id.tvRuntimeHC); String runtimeText = ""; try { runtimeText = runtimeComputation(Float.parseFloat(movie.getRuntime())); } catch (Exception e) { runtimeText = movie.getRuntime(); } runtime.setText(runtimeText); manageEmptyTextfields(runTimeHc, runtime, runtimeText, true); TextView budget = (TextView) findViewById(R.id.tvBudget); TextView budgetHc = (TextView) findViewById(R.id.tvBudgetHC); String budgetText = movie.getBudget(); //Decode the budget if (budgetText.contains("E")) { BigDecimal myNumber = new BigDecimal(budgetText); long budgetLong = myNumber.longValue(); NumberFormat formatter = NumberFormat.getCurrencyInstance(Locale.US); budgetText = formatter.format(budgetLong); budgetText = String.valueOf(budgetText); budgetText = budgetComputation(budgetText); budget.setText(budgetText); manageEmptyTextfields(budgetHc, budget, budgetText, true); } TextView awards = (TextView) findViewById(R.id.tvAwards); TextView awardsHc = (TextView) findViewById(R.id.tvAwardsHC); String awardsText = movie.getAwards(); awards.setText(awardsText); manageEmptyTextfields(awardsHc, awards, awardsText, true); TextView tvDirHc = (TextView) findViewById(R.id.tvDirectorsHC); TextView directors = (TextView) findViewById(R.id.tvDirectors); String directorText = String.valueOf(movie.createTvOutOfList(movie.getDirectors())); directors.setText(directorText); manageEmptyTextfields(tvDirHc, directors, directorText, true); TextView tvWriterHc = (TextView) findViewById(R.id.tvWritersHC); TextView writers = (TextView) findViewById(R.id.tvWriters); String writerText = String.valueOf(movie.createTvOutOfList(movie.getWriters())); writers.setText(writerText); manageEmptyTextfields(tvWriterHc, writers, writerText, true); TextView tvActorsHc = (TextView) findViewById(R.id.tvActorsHC); TextView actors = (TextView) findViewById(R.id.tvActors); String actorText = String.valueOf(movie.createTvOutOfList(movie.getActors())); actors.setText(actorText); manageEmptyTextfields(tvActorsHc, actors, actorText, true); colorIt(actors); if (movie.getActors().size() > 0) { btnActorList.setVisibility(View.VISIBLE); } btnRandomRelatedMovies.setVisibility(View.VISIBLE); btnRelatedMovies.setVisibility(View.VISIBLE); TextView tvRolesHc = (TextView) findViewById(R.id.tvRolesHC); TextView roles = (TextView) findViewById(R.id.tvRoles); ArrayList<String> roleList = movie.getRoles(); if (roleList.size() > 0) { roles.setVisibility(View.VISIBLE); tvRolesHc.setVisibility(View.VISIBLE); roles.setText(String.valueOf(movie.createTvOutOfList(roleList))); } TextView wikiAbstract = (TextView) findViewById(R.id.tvWikiAbstract); wikiAbstract.setText(movie.getWikiAbstract()); if (!"".equals(movie.getImdbId())) { btnImdbPage.setVisibility(View.VISIBLE); } if (!"".equals(movie.getWikiAbstract())) { btnSpoiler.setVisibility(View.VISIBLE); } try { picThread.join(); } catch (InterruptedException e) { e.printStackTrace(); } setProgressBarIndeterminateVisibility(false); }
From source file:org.qucosa.camel.component.sword.SwordConnection.java
public HttpResponse update(String pid, SwordDeposit deposit, Boolean noop, String onBehalfOfHeader) throws Exception { URIBuilder uriBuilder = new URIBuilder(url + "/" + deposit.getCollection() + "/" + pid); HttpPut httpPut = new HttpPut(uriBuilder.build()); httpPut.setHeader("X-No-Op", String.valueOf(noop)); httpPut.setHeader("Content-Type", deposit.getContentType()); if (onBehalfOfHeader != null && !onBehalfOfHeader.isEmpty()) { httpPut.setHeader("X-On-Behalf-Of", onBehalfOfHeader); }// www . j av a 2 s . c o m BasicHttpEntity httpEntity = new BasicHttpEntity(); httpEntity.setContent(toInputStream(deposit.getBody())); httpEntity.setContentType(deposit.getContentType()); httpPut.setEntity(new BufferedHttpEntity(httpEntity)); HttpResponse response = httpClient.execute(httpPut); EntityUtils.consume(response.getEntity()); if (log.isDebugEnabled()) { if (noop) { log.debug("SWORD parameter 'X-No-Op' is '{}'", noop); log.debug("SWORD parameter 'X-On-Behalf-Of' is '{}'", onBehalfOfHeader); log.debug("Content type is '{}'", deposit.getContentType()); log.debug("Posting to SWORD collection '{}'", deposit.getCollection()); } log.debug(response.toString()); } if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { String reason = response.getStatusLine().getReasonPhrase(); throw new Exception(reason); } return response; }
From source file:ch.cyberduck.core.sds.SDSWriteFeature.java
@Override public HttpResponseOutputStream<VersionId> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final CreateFileUploadRequest body = new CreateFileUploadRequest(); body.setParentId(Long.parseLong( new SDSNodeIdProvider(session).getFileid(file.getParent(), new DisabledListProgressListener()))); body.setName(file.getName());/* ww w .ja v a 2 s .c o m*/ body.classification(DEFAULT_CLASSIFICATION); try { final CreateFileUploadResponse response = new NodesApi(session.getClient()) .createFileUpload(StringUtils.EMPTY, body); final String uploadId = response.getUploadId(); final DelayedHttpMultipartEntity entity = new DelayedHttpMultipartEntity(file.getName(), status); final DelayedHttpEntityCallable<VersionId> command = new DelayedHttpEntityCallable<VersionId>() { @Override public VersionId call(final AbstractHttpEntity entity) throws BackgroundException { try { final SDSApiClient client = session.getClient(); final HttpPost request = new HttpPost( String.format("%s/nodes/files/uploads/%s", client.getBasePath(), uploadId)); request.setEntity(entity); request.setHeader(SDSSession.SDS_AUTH_TOKEN_HEADER, StringUtils.EMPTY); request.setHeader(HTTP.CONTENT_TYPE, String.format("multipart/form-data; boundary=%s", DelayedHttpMultipartEntity.DEFAULT_BOUNDARY)); final HttpResponse response = client.getClient().execute(request); try { // Validate response switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_CREATED: // Upload complete break; default: EntityUtils.updateEntity(response, new BufferedHttpEntity(response.getEntity())); throw new SDSExceptionMappingService() .map(new ApiException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase(), Collections.emptyMap(), EntityUtils.toString(response.getEntity()))); } } finally { EntityUtils.consume(response.getEntity()); } final CompleteUploadRequest body = new CompleteUploadRequest(); if (status.isExists()) { body.setResolutionStrategy(CompleteUploadRequest.ResolutionStrategyEnum.OVERWRITE); } if (status.getFilekey() != null) { final ObjectReader reader = session.getClient().getJSON().getContext(null) .readerFor(FileKey.class); final FileKey fileKey = reader.readValue(status.getFilekey().array()); final EncryptedFileKey encryptFileKey = Crypto.encryptFileKey( TripleCryptConverter.toCryptoPlainFileKey(fileKey), TripleCryptConverter .toCryptoUserPublicKey(session.keyPair().getPublicKeyContainer())); body.setFileKey(TripleCryptConverter.toSwaggerFileKey(encryptFileKey)); } final Node upload = new NodesApi(client).completeFileUpload(StringUtils.EMPTY, uploadId, null, body); return new VersionId(String.valueOf(upload.getId())); } catch (IOException e) { throw new HttpExceptionMappingService().map("Upload {0} failed", e, file); } catch (ApiException e) { throw new SDSExceptionMappingService().map("Upload {0} failed", e, file); } catch (CryptoSystemException | InvalidFileKeyException | InvalidKeyPairException e) { throw new CryptoExceptionMappingService().map("Upload {0} failed", e, file); } } @Override public long getContentLength() { return entity.getContentLength(); } }; return this.write(file, status, command, entity); } catch (ApiException e) { throw new SDSExceptionMappingService().map("Upload {0} failed", e, file); } }
From source file:io.milton.httpclient.TransferService.java
/** * Attempt to PUT a file to the server.//from w w w . j a v a 2 s . com * * Now includes an etag check. If you intend to overwrite a file then * include a non-null etag. This will do an if-match check on the server to * ensure you're not overwriting someone else's changes. If the file in new, * the etag given should be null, this will result in an if-none-match: * * check, which will fail if a file already exists * * * * @param encodedUrl * @param content * @param contentLength * @param contentType * @param etag - expected etag on the server if overwriting, or null if a * new file * @param listener * @param context * @return */ public HttpResult put(String encodedUrl, InputStream content, Long contentLength, String contentType, IfMatchCheck etagMatch, ProgressListener listener, HttpContext context) { LogUtils.trace(log, "put: ", encodedUrl); notifyStartRequest(); String s = encodedUrl; HttpPut p = new HttpPut(s); p.addHeader(Request.Header.CONTENT_TYPE.code, contentType); p.addHeader(Request.Header.OVERWRITE.code, "T"); // we always allow overwrites if (etagMatch != null) { if (etagMatch.getEtag() != null) { p.addHeader(Request.Header.IF_MATCH.code, etagMatch.getEtag()); } else { p.addHeader(Request.Header.IF_NONE_MATCH.code, "*"); // this will fail if there is a file with the same name } } NotifyingFileInputStream notifyingIn = null; try { notifyingIn = new NotifyingFileInputStream(content, contentLength, s, listener); HttpEntity requestEntity; if (contentLength == null) { throw new RuntimeException("Content length for input stream is null, you must provide a length"); } else { requestEntity = new InputStreamEntity(notifyingIn, contentLength); requestEntity = new BufferedHttpEntity(requestEntity); // wrap in a buffering thingo to allow repeated requests } p.setEntity(requestEntity); return Utils.executeHttpWithResult(client, p, null, context); } catch (IOException ex) { throw new RuntimeException(ex); } finally { IOUtils.closeQuietly(notifyingIn); notifyFinishRequest(); } }
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;/* w w w . jav a2 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); } }
From source file:gov.jrj.library.http.BinaryHttpResponseHandler.java
@Override 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;/*w w w . ja va2s . co 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); } }
From source file:com.zuowuxuxi.asihttp.AsyncHttpResponseHandler.java
void sendResponseMessage(HttpResponse response) { StatusLine status = response.getStatusLine(); if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase())); } else {// w w w. j a va 2 s. c om try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); } sendSuccessMessage(EntityUtils.toString(entity)); } catch (IOException e) { sendFailureMessage(e); } } }
From source file:com.fihmi.tools.minet.MiHttpResponseHandler.java
void sendResponseMessage(HttpResponse response, final int request_tag) { StatusLine status = response.getStatusLine(); String responseBody = null;//from www . j a va 2s . c om try { HttpEntity entity = null; HttpEntity temp = response.getEntity(); if (temp != null) { entity = new BufferedHttpEntity(temp); responseBody = EntityUtils.toString(entity, "UTF-8"); } } catch (IOException e) { sendFailureMessage(e, (String) null, request_tag); } if (status.getStatusCode() >= 300) { sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody, request_tag); } else { sendSuccessMessage(status.getStatusCode(), response.getAllHeaders(), responseBody, request_tag); } }