List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:com.evernote.android.edam.TAndroidHttpClient.java
public void flush() throws TTransportException { long timer = System.currentTimeMillis(); LOGGER.info((Thread.currentThread().getId()) + ": Creating thrift request"); HttpEntity httpEntity = null;/*from w w w. ja v a 2 s. c om*/ // Extract request and reset buffer try { // Prepare http post request HttpPost request = new HttpPost(url_.toExternalForm()); this.request = request; request.addHeader("Content-Type", "application/x-thrift"); request.addHeader("Cache-Control", "no-transform"); if (customHeaders_ != null) { for (Map.Entry<String, String> header : customHeaders_.entrySet()) { request.addHeader(header.getKey(), header.getValue()); } } InputStreamEntity entity = new InputStreamEntity(requestBuffer_.getInputStream(), requestBuffer_.getSize()); request.setEntity(entity); request.addHeader("Accept", "application/x-thrift"); request.addHeader("User-Agent", userAgent == null ? "Java/THttpClient" : userAgent); request.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); DefaultHttpClient dHTTP = getHTTPClient(); HttpResponse response = dHTTP.execute(request); httpEntity = response.getEntity(); int responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 200) { if (httpEntity != null) { httpEntity.consumeContent(); } throw new TTransportException("HTTP Response code: " + responseCode); } // Read the responses requestBuffer_.reset(); inputStream_ = response.getEntity().getContent(); } catch (IOException iox) { throw new TTransportException(iox); } catch (Exception ex) { throw new TTransportException(ex); } finally { try { requestBuffer_.reset(); } catch (IOException e) { } LOGGER.info((Thread.currentThread().getId()) + ": Response received in: " + (System.currentTimeMillis() - timer) + "ms"); this.request = null; } }
From source file:com.semagia.cassa.client.GraphClient.java
private URI _createGraph(final InputStream in, final MediaType mediaType) throws IOException { final HttpPost request = new HttpPost(_endpoint); final InputStreamEntity entity = new InputStreamEntity(in, -1); entity.setContentType(mediaType != null ? mediaType.toString() : null); request.setEntity(entity);//from w ww .j a v a 2 s. c om final HttpResponse response = execute(request); URI graphURI = null; if (response.getStatusLine().getStatusCode() == 201) { final Header location = response.getFirstHeader("location"); graphURI = location != null ? URI.create(location.getValue()) : null; } request.abort(); return graphURI; }
From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcap2Adapter.java
/** * @inheritDoc/*ww w . java 2 s. c o m*/ */ public void writeObjectFromStream(final String targetNode, final String targetPath, final InputStream is, final FileMetadata ingestionMetadata) throws StorageAdapterException { HttpHost httpHost = new HttpHost(targetNode, profile.getPort(), profile.getProtocol()); String filePath = targetPath; if (!filePath.startsWith(HttpGatewayConstants.METADATA_MOUNT_URL_DIR)) { filePath = getProfile().resolvePath(filePath); } String queryString = null; if (ingestionMetadata != null) { queryString = generateQueryParameters(ingestionMetadata, false); } URI uri = null; try { uri = URIUtils.createURI(profile.getProtocol(), targetNode, profile.getPort(), filePath, queryString, null); } catch (URISyntaxException e) { LOG.log(Level.WARNING, "Unexpected error generating put URI for : " + targetPath); throw new StorageAdapterLiteralException("Error writing object to the server", e); } HttpPut request = new HttpPut(uri); InputStreamEntity isEntity = new InputStreamEntity(is, -1); request.setEntity(isEntity); request.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.TRUE); request.getParams().setParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE, 100); // Eventually we will just return this cookie which will be passed back to the caller. HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost); synchronized (savingCookieLock) { if (savedCookie != null) { throw new RuntimeException( "This adapter already has a current connection to host -- cannot create two at once."); } savedCookie = cookie; } try { executeMethod(cookie); this.handleHttpResponse(cookie.getResponse(), "writing", targetPath); } catch (IOException e) { this.handleIOExceptionFromRequest(e, "writing", targetPath); } finally { close(); } }
From source file:com.nominanuda.web.http.ServletHelper.java
@SuppressWarnings("unchecked") private HttpEntity buildEntity(HttpServletRequest servletRequest, final InputStream is, long contentLength, String ct, String cenc) throws IOException { if (ServletFileUpload.isMultipartContent(servletRequest)) { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> items; try {//from w w w .jav a 2 s . c o m items = upload.parseRequest(new HttpServletRequestWrapper(servletRequest) { public ServletInputStream getInputStream() throws IOException { return new ServletInputStream() { public int read() throws IOException { return is.read(); } public int read(byte[] arg0) throws IOException { return is.read(arg0); } public int read(byte[] b, int off, int len) throws IOException { return is.read(b, off, len); } //@Override @SuppressWarnings("unused") public boolean isFinished() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public boolean isReady() { Check.illegalstate.fail(NOT_IMPLEMENTED); return false; } //@Override @SuppressWarnings("unused") public void setReadListener(ReadListener arg0) { Check.illegalstate.fail(NOT_IMPLEMENTED); } }; } }); } catch (FileUploadException e) { throw new IOException(e); } MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); for (FileItem i : items) { multipartEntity.addPart(i.getFieldName(), new InputStreamBody(i.getInputStream(), i.getName())); } return multipartEntity; } else { InputStreamEntity entity = new InputStreamEntity(is, contentLength); entity.setContentType(ct); if (cenc != null) { entity.setContentEncoding(cenc); } return entity; } }
From source file:org.sonatype.nexus.proxy.storage.remote.httpclient.HttpClientRemoteStorage.java
@Override public void storeItem(final ProxyRepository repository, final StorageItem item) throws UnsupportedStorageOperationException, RemoteStorageException { if (!(item instanceof StorageFileItem)) { throw new UnsupportedStorageOperationException("Storing of non-files remotely is not supported!"); }// w w w. jav a 2 s. com final StorageFileItem fileItem = (StorageFileItem) item; final ResourceStoreRequest request = new ResourceStoreRequest(item); final URL remoteUrl = appendQueryString(getAbsoluteUrlFromBase(repository, request), repository); final HttpPut method = new HttpPut(remoteUrl.toExternalForm()); final InputStreamEntity entity; try { entity = new InputStreamEntity(fileItem.getInputStream(), fileItem.getLength()); } catch (IOException e) { throw new RemoteStorageException( e.getMessage() + " [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteUrl.toString() + "\"]", e); } entity.setContentType(fileItem.getMimeType()); method.setEntity(entity); final HttpResponse httpResponse = executeRequestAndRelease(repository, request, method); final int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED && statusCode != HttpStatus.SC_NO_CONTENT && statusCode != HttpStatus.SC_ACCEPTED) { throw new RemoteStorageException("Unexpected response code while executing " + method.getMethod() + " method [repositoryId=\"" + repository.getId() + "\", requestPath=\"" + request.getRequestPath() + "\", remoteUrl=\"" + remoteUrl.toString() + "\"]. Expected: \"any success (2xx)\". Received: " + statusCode + " : " + httpResponse.getStatusLine().getReasonPhrase()); } }
From source file:org.kairosdb.datastore.remote.RemoteDatastore.java
/** Sends a single zip file/*from w w w. j a v a2s. com*/ @param zipFile Name of the zip file in the data directory. @throws IOException */ private void sendZipfile(String zipFile) throws IOException { logger.debug("Sending {}", zipFile); HttpPost post = new HttpPost(m_remoteUrl + "/api/v1/datapoints"); File zipFileObj = new File(m_dataDirectory, zipFile); FileInputStream zipStream = new FileInputStream(zipFileObj); post.setHeader("Content-Type", "application/gzip"); post.setEntity(new InputStreamEntity(zipStream, zipFileObj.length())); HttpResponse response = m_client.execute(post); zipStream.close(); if (response.getStatusLine().getStatusCode() == 204) { zipFileObj.delete(); } else { ByteArrayOutputStream body = new ByteArrayOutputStream(); response.getEntity().writeTo(body); logger.error("Unable to send file " + zipFile + ": " + response.getStatusLine() + " - " + body.toString("UTF-8")); } }
From source file:com.fujitsu.dc.core.rs.box.DcEngineSvcCollectionResource.java
/** * relay??./*from w w w .j a va 2 s. c o m*/ * @param method * @param uriInfo URI * @param path ?? * @param headers * @param is * @return JAX-RS Response */ public Response relaycommon(String method, UriInfo uriInfo, String path, HttpHeaders headers, InputStream is) { String cellName = this.davRsCmp.getCell().getName(); String boxName = this.davRsCmp.getBox().getName(); String requestUrl = String.format("http://%s:%s/%s/%s/%s/service/%s", DcCoreConfig.getEngineHost(), DcCoreConfig.getEnginePort(), DcCoreConfig.getEnginePath(), cellName, boxName, path); // baseUrl? String baseUrl = uriInfo.getBaseUri().toString(); // ??? HttpClient client = new DefaultHttpClient(); HttpUriRequest req = null; if (method.equals(HttpMethod.POST)) { HttpPost post = new HttpPost(requestUrl); InputStreamEntity ise = new InputStreamEntity(is, -1); ise.setChunked(true); post.setEntity(ise); req = post; } else if (method.equals(HttpMethod.PUT)) { HttpPut put = new HttpPut(requestUrl); InputStreamEntity ise = new InputStreamEntity(is, -1); ise.setChunked(true); put.setEntity(ise); req = put; } else if (method.equals(HttpMethod.DELETE)) { HttpDelete delete = new HttpDelete(requestUrl); req = delete; } else { HttpGet get = new HttpGet(requestUrl); req = get; } req.addHeader("X-Baseurl", baseUrl); req.addHeader("X-Request-Uri", uriInfo.getRequestUri().toString()); // ?INDEXIDTYPE? if (davCmp instanceof DavCmpEsImpl) { DavCmpEsImpl test = (DavCmpEsImpl) davCmp; req.addHeader("X-Dc-Es-Index", test.getEsColType().getIndex().getName()); req.addHeader("X-Dc-Es-Id", test.getNodeId()); req.addHeader("X-Dc-Es-Type", test.getEsColType().getType()); req.addHeader("X-Dc-Es-Routing-Id", this.davRsCmp.getCell().getId()); req.addHeader("X-Dc-Box-Schema", this.davRsCmp.getBox().getSchema()); } // ??? MultivaluedMap<String, String> multivalueHeaders = headers.getRequestHeaders(); for (Iterator<Entry<String, List<String>>> it = multivalueHeaders.entrySet().iterator(); it.hasNext();) { Entry<String, List<String>> entry = it.next(); String key = (String) entry.getKey(); if (key.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) { continue; } List<String> valueList = (List<String>) entry.getValue(); for (Iterator<String> i = valueList.iterator(); i.hasNext();) { String value = (String) i.next(); req.setHeader(key, value); } } if (log.isDebugEnabled()) { log.debug("?EngineRelay " + req.getMethod() + " " + req.getURI()); Header[] reqHeaders = req.getAllHeaders(); for (int i = 0; i < reqHeaders.length; i++) { log.debug("RelayHeader[" + reqHeaders[i].getName() + "] : " + reqHeaders[i].getValue()); } } // Engine?? HttpResponse objResponse = null; try { objResponse = client.execute(req); } catch (ClientProtocolException e) { throw DcCoreException.ServiceCollection.SC_INVALID_HTTP_RESPONSE_ERROR; } catch (Exception ioe) { throw DcCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(ioe); } // ResponseBuilder res = Response.status(objResponse.getStatusLine().getStatusCode()); Header[] headersResEngine = objResponse.getAllHeaders(); // ? for (int i = 0; i < headersResEngine.length; i++) { // Engine????Transfer-Encoding???? // ?MW????????Content-Length???Transfer-Encoding???? // 2?????????????????????? if ("Transfer-Encoding".equalsIgnoreCase(headersResEngine[i].getName())) { continue; } // Engine????Date???? // Web??MW?Jetty???2????????? if (HttpHeaders.DATE.equalsIgnoreCase(headersResEngine[i].getName())) { continue; } res.header(headersResEngine[i].getName(), headersResEngine[i].getValue()); } InputStream isResBody = null; // ? HttpEntity entity = objResponse.getEntity(); if (entity != null) { try { isResBody = entity.getContent(); } catch (IllegalStateException e) { throw DcCoreException.ServiceCollection.SC_UNKNOWN_ERROR.reason(e); } catch (IOException e) { throw DcCoreException.ServiceCollection.SC_ENGINE_CONNECTION_ERROR.reason(e); } final InputStream isInvariable = isResBody; // ?? StreamingOutput strOutput = new StreamingOutput() { @Override public void write(final OutputStream os) throws IOException { int chr; try { while ((chr = isInvariable.read()) != -1) { os.write(chr); } } finally { isInvariable.close(); } } }; res.entity(strOutput); } // ?? return res.build(); }
From source file:org.iff.infra.util.servlet.ProxyServlet.java
@Override protected void service(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 String method = servletRequest.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(servletRequest); HttpRequest proxyRequest;/*from w ww . j a v a 2 s . co m*/ //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. if (servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) != null || servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING) != null) { HttpEntityEnclosingRequest eProxyRequest = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); // Add the input entity (streamed) // note: we don't bother ensuring we close the servletInputStream since the container handles it eProxyRequest.setEntity( new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); setXForwardedForHeader(servletRequest, proxyRequest); {//add by tylerchen String header = initParameterMap.get("header"); if (header != null) { String[] split = header.split("@@@"); for (String s : split) { String[] headerPaire = s.split("="); if (headerPaire.length == 2) { proxyRequest.addHeader(headerPaire[0], headerPaire[1]); } } } } HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(URIUtils.extractHost(targetUriObj), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send //TODO copy response headers? 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); if ("true".equals(initParameterMap.get("cached"))) {//add cache by tylerchen //servlet?? //?????20 //20????servlet HttpServletResponse response = (HttpServletResponse) servletResponse; Date date = new Date(); response.setDateHeader("Last-Modified", date.getTime()); //Last-Modified:??? response.setDateHeader("Expires", date.getTime() * 100); //Expires:? response.setHeader("Cache-Control", "public"); //Cache-Control???,public:????? response.setHeader("Cache-Control", "max-age=" + date.getTime() * 100); response.setHeader("Pragma", "Pragma"); //Pragma:??Pragmano-cache? //??????? /*response.setHeader( "Pragma", "no-cache" ); response.setDateHeader("Expires", 0); response.addHeader( "Cache-Control", "no-cache" );//????? response.addHeader( "Cache-Control", "no-store" );//???? response.addHeader( "Cache-Control", "must-revalidate" );*///?????? } // 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; //noinspection ConstantConditions if (e instanceof IOException) throw (IOException) e; throw new RuntimeException(e); } finally { // make sure the entire entity was consumed, so the connection is released if (proxyResponse != null) consumeQuietly(proxyResponse.getEntity()); //Note: Don't need to close servlet outputStream: // http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter } }
From source file:eu.europa.esig.dss.client.http.commons.FileCacheDataLoader.java
@Override public byte[] post(final String urlString, final byte[] content) throws DSSException { final String fileName = ResourceLoader.getNormalizedFileName(urlString); // 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 byte[] digest = DSSUtils.digest(DigestAlgorithm.MD5, content); final String digestHexEncoded = DSSUtils.toHex(digest); final String cacheFileName = fileName + "." + digestHexEncoded; final File file = getCacheFile(cacheFileName); if (file.exists()) { LOG.debug("Cached file was used"); final byte[] byteArray = DSSUtils.toByteArray(file); return byteArray; } else {// ww w .j a v a 2 s . co m LOG.debug("There is no cached file!"); } final byte[] returnedBytes; if (!isNetworkProtocol(urlString)) { final String resourcePath = resourceLoader.getAbsoluteResourceFolder(urlString.trim()); final File fileResource = new File(resourcePath); returnedBytes = DSSUtils.toByteArray(fileResource); return returnedBytes; } HttpPost httpRequest = null; HttpResponse httpResponse = null; try { final URI uri = URI.create(urlString.trim()); httpRequest = new HttpPost(uri); final ByteArrayInputStream bis = new ByteArrayInputStream(content); final HttpEntity httpEntity = new InputStreamEntity(bis, content.length); final HttpEntity requestEntity = new BufferedHttpEntity(httpEntity); httpRequest.setEntity(requestEntity); if (contentType != null) { httpRequest.setHeader(CONTENT_TYPE, contentType); } httpResponse = super.getHttpResponse(httpRequest, urlString); returnedBytes = readHttpResponse(urlString, httpResponse); if (returnedBytes.length != 0) { final File cacheFile = getCacheFile(cacheFileName); DSSUtils.saveToFile(returnedBytes, cacheFile); } } catch (IOException e) { throw new DSSException(e); } finally { if (httpRequest != null) { httpRequest.releaseConnection(); } if (httpResponse != null) { EntityUtils.consumeQuietly(httpResponse.getEntity()); } } return returnedBytes; }