List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:at.tomtasche.reader.background.UpLoader.java
@Override public Document loadInBackground() { if (uri == DocumentLoader.URI_INTRO) { cancelLoad();/*from w w w . j a va 2 s . c o m*/ return null; } String type = getContext().getContentResolver().getType(uri); if (type == null) type = URLConnection.guessContentTypeFromName(uri.toString()); if (type == null) { try { InputStream stream = getContext().getContentResolver().openInputStream(uri); try { type = URLConnection.guessContentTypeFromStream(stream); } finally { stream.close(); } } catch (Exception e) { e.printStackTrace(); } } if (type != null && (type.equals("text/html") || type.equals("text/plain") || type.equals("image/png") || type.equals("image/jpeg"))) { try { document = new Document(null); document.addPage(new Page("Document", new URI(uri.toString()), 0)); return document; } catch (URISyntaxException e) { e.printStackTrace(); } } String name = uri.getLastPathSegment(); try { name = URLEncoder.encode(name, "UTF-8"); type = URLEncoder.encode(type, "UTF-8"); } catch (Exception e) { } HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(SERVER_URL + "file?name=" + name + "&type=" + type); InputStream stream = null; try { stream = getContext().getContentResolver().openInputStream(uri); InputStreamEntity reqEntity = new InputStreamEntity(stream, -1); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { Map<String, Object> container = new Gson().fromJson(EntityUtils.toString(response.getEntity()), Map.class); String key = container.get("key").toString(); URI viewerUri = URI.create("https://docs.google.com/viewer?embedded=true&url=" + URLEncoder.encode(SERVER_URL + "file?key=" + key, "UTF-8")); document = new Document(null); document.addPage(new Page("Document", viewerUri, 0)); } else { throw new RuntimeException("server couldn't handle request"); } } catch (Throwable e) { e.printStackTrace(); lastError = e; } finally { try { if (stream != null) { stream.close(); } } catch (IOException e) { } httpclient.getConnectionManager().shutdown(); } return document; }
From source file:org.apache.olingo.client.core.communication.request.AsyncRequestWrapperImpl.java
protected AsyncRequestWrapperImpl(final ODataClient odataClient, final ODataRequest odataRequest) { this.odataRequest = odataRequest; this.odataRequest.setAccept(this.odataRequest.getAccept()); this.odataRequest.setContentType(this.odataRequest.getContentType()); extendHeader(HttpHeader.PREFER, new ODataPreferences().respondAsync()); this.odataClient = odataClient; final HttpMethod method = odataRequest.getMethod(); // target uri this.uri = odataRequest.getURI(); HttpClient _httpClient = odataClient.getConfiguration().getHttpClientFactory().create(method, this.uri); if (odataClient.getConfiguration().isGzipCompression()) { _httpClient = new DecompressingHttpClient(_httpClient); }//from w ww .java 2 s. c o m this.httpClient = _httpClient; this.request = odataClient.getConfiguration().getHttpUriRequestFactory().create(method, this.uri); if (request instanceof HttpEntityEnclosingRequestBase) { if (odataRequest instanceof AbstractODataBasicRequest) { AbstractODataBasicRequest<?> br = (AbstractODataBasicRequest<?>) odataRequest; HttpEntityEnclosingRequestBase httpRequest = ((HttpEntityEnclosingRequestBase) request); httpRequest.setEntity(new InputStreamEntity(br.getPayload(), -1)); } } }
From source file:org.chaplib.TestHttpResource.java
@Test public void closesConnectionIfParserThrowsException() throws Exception { response.setEntity(new InputStreamEntity(mockInputStream, -1)); when(mockHttpClient.execute(any(HttpUriRequest.class))).thenReturn(response); when(mockParser.parse(entity)).thenThrow(new RuntimeException()); try {/*ww w . ja v a 2s .co m*/ impl.value(mockParser); } catch (RuntimeException expected) { } verify(mockInputStream, atLeastOnce()).close(); }
From source file:org.dataconservancy.dcs.access.server.FileUploadServlet.java
private void uploadfile(String depositurl, String filename, InputStream is, HttpServletResponse resp) throws IOException { /* File tmp = null; FileOutputStream fos = null;/* w w w . j a va 2 s .com*/ PostMethod post = null; //System.out.println(filename + " -> " + depositurl); */ try { /* tmp = File.createTempFile("fileupload", null); fos = new FileOutputStream(tmp); FileUtil.copy(is, fos); HttpClient client = new HttpClient(); post = new PostMethod(depositurl); Part[] parts = {new FilePart(filename, tmp)}; post.setRequestEntity(new MultipartRequestEntity(parts, post .getParams())); */ org.apache.http.client.HttpClient client = new DefaultHttpClient(); HttpPost post = new HttpPost(depositurl); InputStreamEntity data = new InputStreamEntity(is, -1); data.setContentType("binary/octet-stream"); data.setChunked(false); post.setEntity(data); HttpResponse response = client.execute(post); System.out.println(response.toString()); int status = 202;//response.getStatusLine(); // int status = client.executeMethod(post); if (status == HttpStatus.SC_ACCEPTED || status == HttpStatus.SC_CREATED) { resp.setStatus(status); String src = response.getHeaders("X-dcs-src")[0].getValue(); String atomurl = response.getHeaders("Location")[0].getValue(); resp.setContentType("text/html"); resp.getWriter().print("<html><body><p>^" + src + "^" + atomurl + "^</p></body></html>"); resp.flushBuffer(); } else { resp.sendError(status, response.getStatusLine().toString()); return; } } finally { /* if (tmp != null) { tmp.delete(); } if (is != null) { is.close(); } if (fos != null) { fos.close(); } if (post != null) { post.releaseConnection(); }*/ } }
From source file:com.ocp.picasa.GDataClient.java
public void putStream(String feedUrl, InputStream stream, String contentType, Operation operation) throws IOException { InputStreamEntity entity = new InputStreamEntity(stream, -1); entity.setContentType(contentType);/* w ww . j a va 2s .c om*/ HttpPost post = new HttpPost(feedUrl); post.setHeader(X_HTTP_METHOD_OVERRIDE, "PUT"); post.setEntity(entity); callMethod(post, operation); }
From source file:com.kolich.http.common.HttpClient4ClosureBase.java
public T put(final HttpPut put, final InputStream is, final long length, final String contentType, final HttpContext context) { if (is != null) { final InputStreamEntity entity = new InputStreamEntity(is, length); if (contentType != null) { entity.setContentType(contentType); }//from w w w . j ava 2s .co m put.setEntity(entity); } return request(put, context); }
From source file:org.fashiontec.bodyapps.sync.SyncPic.java
/** * Multipart put request for images.//from www .j a v a 2 s. co m * @param url * @param path * @return */ public HttpResponse put(String url, String path) { HttpResponse response = null; try { File file = new File(path); HttpClient client = new DefaultHttpClient(); HttpPut post = new HttpPut(url); InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file.getPath()), file.length()); entity.setContentType("image/jpeg"); entity.setChunked(true); post.setEntity(entity); response = client.execute(post); } catch (IOException e) { e.printStackTrace(); } return response; }
From source file:com.jayway.restassured.internal.http.EncoderRegistry.java
/** * Default request encoder for a binary stream. Acceptable argument * types are://from ww w. j a va 2 s.com * <ul> * <li>InputStream</li> * <li>byte[] / ByteArrayOutputStream</li> * <li>Closure</li> * </ul> * If a closure is given, it is executed with an OutputStream passed * as the single closure argument. Any data sent to the stream from the * body of the closure is used as the request content body. * * @param data * @return an {@link HttpEntity} encapsulating this request data * @throws UnsupportedEncodingException */ public InputStreamEntity encodeStream(Object contentType, Object data) throws UnsupportedEncodingException { InputStreamEntity entity = null; if (data instanceof ByteArrayInputStream) { // special case for ByteArrayIS so that we can set the content length. ByteArrayInputStream in = ((ByteArrayInputStream) data); entity = new InputStreamEntity(in, in.available()); } else if (data instanceof InputStream) { entity = new InputStreamEntity((InputStream) data, -1); } else if (data instanceof File) { FileInputStream fileInputStream; File file = (File) data; try { fileInputStream = new FileInputStream(file); } catch (FileNotFoundException e) { throw new RuntimeException("File " + file.getPath() + " not found", e); } entity = new InputStreamEntity(fileInputStream, -1); } else if (data instanceof byte[]) { byte[] out = ((byte[]) data); entity = new InputStreamEntity(new ByteArrayInputStream(out), out.length); } else if (data instanceof ByteArrayOutputStream) { ByteArrayOutputStream out = ((ByteArrayOutputStream) data); entity = new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()), out.size()); } else if (data instanceof Closure) { ByteArrayOutputStream out = new ByteArrayOutputStream(); ((Closure) data).call(out); // data is written to out entity = new InputStreamEntity(new ByteArrayInputStream(out.toByteArray()), out.size()); } if (entity == null) throw new IllegalArgumentException("Don't know how to encode " + data + " as a byte stream.\n\nPlease use EncoderConfig (EncoderConfig#encodeContentTypeAs) to specify how to serialize data for this content-type.\n" + "For example: \"given().config(RestAssured.config().encoderConfig(encoderConfig().encodeContentTypeAs(\"" + ContentTypeExtractor.getContentTypeWithoutCharset(contentTypeToString(contentType)) + "\", ContentType.TEXT))). ..\""); entity.setContentType(contentTypeToString(contentType)); return entity; }
From source file:de.dentrassi.pm.jenkins.UploaderV3.java
@Override public boolean complete() { if (this.failed) { return false; }/* ww w. j a v a 2 s. co m*/ try { closeTransfer(); final URIBuilder uri = new URIBuilder(String.format("%s/api/v3/upload/archive/channel/%s", this.serverUrl, URIUtil.encodeWithinPath(this.channelId))); this.listener.getLogger().println("API endpoint: " + uri.build().toString()); final HttpPut httppost = new HttpPut(uri.build()); final String encodedAuth = Base64 .encodeBase64String(("deploy:" + this.deployKey).getBytes("ISO-8859-1")); httppost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encodedAuth); final InputStream stream = new FileInputStream(this.tempFile); try { httppost.setEntity(new InputStreamEntity(stream, this.tempFile.length())); final HttpResponse response = this.client.execute(httppost); final HttpEntity resEntity = response.getEntity(); this.listener.getLogger().println("Call returned: " + response.getStatusLine()); if (resEntity != null) { switch (response.getStatusLine().getStatusCode()) { case 200: processUploadResult(makeString(resEntity)); return true; case 404: this.listener.error( "Failed to find upload endpoint V3. This could mean that you configured a wrong server URL or that the server does not support the Upload V3. You will need a version 0.14+ of Eclipse Package Drone. It could also mean that you did use wrong credentials."); return false; default: if (!handleError(response)) { addErrorMessage("Failed to upload: " + response.getStatusLine()); } return false; } } addErrorMessage("Did not receive a result"); return false; } finally { stream.close(); } } catch (final Exception e) { e.printStackTrace(this.listener.error("Failed to perform archive upload")); return false; } }