List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:eu.europa.ec.markt.dss.validation102853.https.CommonsDataLoader.java
@Override public byte[] post(final String url, final byte[] content) throws DSSException { LOG.debug("Fetching data via POST from url " + url); HttpPost httpRequest = null;/*from w w w. j a v a2 s.c om*/ HttpResponse httpResponse = null; try { final URI uri = URI.create(url.trim()); httpRequest = new HttpPost(uri); // The length for the InputStreamEntity is needed, because some receivers (on the other side) need this information. // To determine the length, we cannot read the content-stream up to the end and re-use it afterwards. // This is because, it may not be possible to reset the stream (= go to position 0). // So, the solution is to cache temporarily the complete content data (as we do not expect much here) in a byte-array. final ByteArrayInputStream bis = new ByteArrayInputStream(content); final HttpEntity requestEntity = new InputStreamEntity(bis, content.length); httpRequest.setEntity(requestEntity); if (contentType != null) { httpRequest.setHeader(CONTENT_TYPE, contentType); } httpResponse = getHttpResponse(httpRequest, url); final byte[] returnedBytes = readHttpResponse(url, httpResponse); return returnedBytes; } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } }
From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
@SuppressWarnings("deprecation") private void doProxy(String remoteUrl, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { // Make the Request //note: we won't transfer the protocol version because I'm not sure it would truly be compatible try {//from ww w. j a v a 2 s . c o m this.targetUri = new URI(remoteUrl); } catch (URISyntaxException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } //Need to handle https, but think about "restricted" layers for now. Some institutions don't really have good protection for restricted layers. Does this open up potential for security //problems for those folks? if (servletRequest.getScheme().equals("https")) { //actually, what matters the most is if the remote url is https } BasicHttpEntityEnclosingRequest proxyRequest = new BasicHttpEntityEnclosingRequest( servletRequest.getMethod(), rewriteUrlFromRequest(servletRequest)); copyRequestHeaders(servletRequest, proxyRequest); // Add the input entity (streamed) then execute the request. HttpResponse proxyResponse = null; InputStream servletRequestInputStream = servletRequest.getInputStream(); try { try { proxyRequest.setEntity( new InputStreamEntity(servletRequestInputStream, servletRequest.getContentLength())); // Execute the request logger.debug("proxy " + servletRequest.getMethod() + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUri), proxyRequest); } finally { closeQuietly(servletRequestInputStream); } // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); logger.info("Status from remote server: " + Integer.toString(statusCode)); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { EntityUtils.consume(proxyResponse.getEntity()); return; } // Pass the response code. This method with the "reason phrase" is deprecated but it's the only way to pass the // reason along too. //noinspection deprecation servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); copyResponseHeaders(proxyResponse, servletResponse); // Send the content to the client copyResponseEntity(proxyResponse, servletResponse); } catch (Exception e) { //abort request, according to best practice with HttpClient if (proxyRequest instanceof AbortableHttpRequest) { AbortableHttpRequest abortableHttpRequest = (AbortableHttpRequest) proxyRequest; abortableHttpRequest.abort(); } if (e instanceof RuntimeException) throw (RuntimeException) e; if (e instanceof ServletException) throw (ServletException) e; throw new RuntimeException(e); } }
From source file:android.net.http.Request.java
/** * Supply an InputStream that provides the body of a request. It's * not great that the caller must also provide the length of the data * returned by that InputStream, but the client needs to know up * front, and I'm not sure how to get this out of the InputStream * itself without a costly readthrough. I'm not sure skip() would * do what we want. If you know a better way, please let me know. *///from w w w.j a va 2s. c o m private void setBodyProvider(InputStream bodyProvider, int bodyLength) { if (!bodyProvider.markSupported()) { throw new IllegalArgumentException("bodyProvider must support mark()"); } // Mark beginning of stream bodyProvider.mark(Integer.MAX_VALUE); ((BasicHttpEntityEnclosingRequest) mHttpRequest).setEntity(new InputStreamEntity(bodyProvider, bodyLength)); }
From source file:org.commonjava.couch.db.CouchManager.java
public void attach(final CouchDocument doc, final Attachment attachment) throws CouchDBException { if (!documentRevisionExists(doc)) { throw new CouchDBException("Cannot attach to a non-existent document: %s", doc.getCouchDocId()); }/*from ww w . j ava 2s.c om*/ String url; try { url = buildUrl(config.getDatabaseUrl(), Collections.singletonMap(REV, doc.getCouchDocRev()), doc.getCouchDocId(), attachment.getName()); } catch (final MalformedURLException e) { throw new CouchDBException("Failed to format attachment URL for: %s to document: %s. Error: %s", e, attachment.getName(), doc.getCouchDocId(), e.getMessage()); } LOGGER.info("Attaching " + attachment.getName() + " to document: " + doc.getCouchDocId() + "\nURL: " + url); final HttpPut request = new HttpPut(url); request.setHeader(HttpHeaders.CONTENT_TYPE, attachment.getContentType()); try { request.setEntity(new InputStreamEntity(attachment.getData(), attachment.getContentLength())); } catch (final IOException e) { throw new CouchDBException("Failed to read attachment data: %s. Error: %s", e, attachment.getName(), e.getMessage()); } client.executeHttp(request, SC_CREATED, "Failed to attach to document"); }
From source file:edu.isi.misd.tagfiler.client.JakartaClient.java
/** * Uploads a file block.// w ww . ja v a 2 s. c om * * @param url * the query url * @param inputStream * the InputStream where to read from * @param length * the number of bytes to read * @param first * the first byte to read * @param fileLength * the file length * @param cookie * the cookie to be set in the request * @return the HTTP Response */ public ClientURLResponse postFile(String url, InputStream inputStream, long length, long first, long fileLength, String cookie) { HttpPut httpput = new HttpPut(url); httpput.setHeader("Content-Type", "application/octet-stream"); if (first != 0) { httpput.setHeader("Content-Range", "bytes " + first + "-" + (first + length - 1) + "/" + fileLength); } InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream, length); inputStreamEntity.setChunked(false); httpput.setEntity(inputStreamEntity); return execute(httpput, cookie); }
From source file:fr.smile.liferay.EsigatePortlet.java
/** * Transform request to IncominqRequest/*from ww w . j a va2 s .c o m*/ * * @param request * @param method * @return an incoming request * @throws IOException */ public IncomingRequest create(PortletRequest request, String method) throws IOException { HttpServletRequest httpServletRequest = PortalUtil .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request)); StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL); StringBuilder query = new StringBuilder(); Enumeration<String> parameters = request.getParameterNames(); String sep = ""; while (parameters.hasMoreElements()) { String name = parameters.nextElement(); String[] values = request.getParameterValues(name); if (!name.equals(ACTION_PARAMETER)) { for (String value : values) { query.append(sep); query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8")); sep = "&"; } } } ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0); if (method.equals("GET")) { if (!query.toString().isEmpty()) { if (!uri.toString().contains("?")) { uri.append("?"); } else { uri.append("&"); } uri.append(query); } } if (LOG.isDebugEnabled()) { LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion " + protocolVersion); } IncomingRequest.Builder builder = IncomingRequest .builder(new BasicRequestLine(method, uri.toString(), protocolVersion)); if (method.equals("POST")) { // create entity InputStream inputStream = IOUtils.toInputStream(query.toString()); if (inputStream != null) { // Copy entity-related headers InputStreamEntity entity = new InputStreamEntity(inputStream, query.length()); String contentTypeHeader = httpServletRequest.getContentType(); if (contentTypeHeader != null) { entity.setContentType(contentTypeHeader); } String contentEncodingHeader = httpServletRequest.getCharacterEncoding(); if (contentEncodingHeader != null) { entity.setContentEncoding(contentEncodingHeader); } builder.setEntity(entity); } } HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null); builder.setContext(context); builder.setRemoteAddr(httpServletRequest.getRemoteAddr()); builder.setRemoteUser(request.getRemoteUser()); HttpSession session = httpServletRequest.getSession(false); if (session != null) { builder.setSessionId(session.getId()); } builder.setUserPrincipal(request.getUserPrincipal()); // Copy cookies javax.servlet.http.Cookie[] src = request.getCookies(); if (src != null) { LOG.debug("Copying " + src.length + " cookie(s) to response."); for (int i = 0; i < src.length; i++) { javax.servlet.http.Cookie c = src[i]; BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue()); dest.setSecure(c.getSecure()); dest.setDomain(c.getDomain()); dest.setPath(c.getPath()); dest.setComment(c.getComment()); dest.setVersion(c.getVersion()); builder.addCookie(dest); } } builder.setSession(new HttpServletSession(httpServletRequest)); IncomingRequest incomingRequest = builder.build(); return incomingRequest; }
From source file:com.iflytek.cssp.SwiftAPI.SwiftClient.java
public SwiftClientResponse PutFaceVerity(String url, String Container, String object_name, InputStream content, long content_length, Map<String, String> query, String accesskey, String secretkey) throws IOException, CSSPException { BasicHttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeout); HttpConnectionParams.setSoTimeout(httpParameters, soTimeout); HttpClient httpClient = new DefaultHttpClient(httpParameters); Map<String, String> headers = new LinkedHashMap<String, String>(); ParameterHandler add_query = new ParameterHandler(); String query_string = ""; query_string = add_query.add_query(query); String url_storage = url;/* w w w .ja va2s .c o m*/ if (Container != null) { url_storage += "/" + encode(Container); } if (object_name != null) { url_storage += "/" + encode(object_name) + query_string; } HttpPut httpput = new HttpPut(url_storage); //httpput.addHeader(AUTH_TOKEN, token); CSSPSignature signature = new CSSPSignature("PUT", null, "/" + Container + "/" + object_name, null, null); signature.getDate(); String auth = signature.getSinature(); String signa = signature.HmacSHA1Encrypt(auth, secretkey); httpput.addHeader(DATE, signature.Date); httpput.addHeader(AUTH, CSSP + accesskey + ":" + signa); if (content != null) { InputStreamEntity body = new InputStreamEntity(content, content_length); body.setChunked(false); httpput.setEntity(body); } HttpResponse response = httpClient.execute(httpput); Header[] Headers = response.getAllHeaders(); for (Header Header : Headers) { headers.put(Header.getName(), Header.getValue()); } if (isMatch_2XX(response.getStatusLine().getStatusCode())) { return new SwiftClientResponse(headers, response.getStatusLine().getStatusCode(), response.getStatusLine(), null, null); } else { logger.error("[put object: error, StatusCode is ]" + response.getStatusLine().getStatusCode()); return new ExceptionHandle().ContainerExceptionHandle(response, headers); } }