List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:com.amazon.s3.http.RepeatableInputStreamRequestEntity.java
/** * Creates a new RepeatableInputStreamRequestEntity using the information * from the specified request. If the input stream containing the request's * contents is repeatable, then this RequestEntity will report as being * repeatable./*from w w w. j a v a 2 s .c om*/ * * @param request * The details of the request being written out (content type, * content length, and content). */ RepeatableInputStreamRequestEntity(Request<?> request) { setChunked(false); /* * If we don't specify a content length when we instantiate our * InputStreamRequestEntity, then HttpClient will attempt to buffer the * entire stream contents into memory to determine the content length. * * TODO: It'd be nice to have easier access to content length and * content type from the request, instead of having to look directly * into the headers. */ long contentLength = -1; try { String contentLengthString = request.getHeaders().get("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } } catch (NumberFormatException nfe) { Log.w(TAG, "Unable to parse content length from request. " + "Buffering contents in memory."); } String contentType = request.getHeaders().get("Content-Type"); inputStreamRequestEntity = new InputStreamEntity(request.getContent(), contentLength); inputStreamRequestEntity.setContentType(contentType); content = request.getContent(); setContent(content); setContentType(contentType); setContentLength(contentLength); }
From source file:org.Cherry.Modules.Web.Engine.JSONRequestHandler.java
@Override public void handle(final RequestCommand command) throws HttpException, IOException { final CallDef call = scanRESTBeanURI(command.getUri()); final JSONAgentDefinition jsonAgent = getController(call.getControllerURI()); assert null != jsonAgent : "Undefined controller for URI [" + command.getUri() + "]"; final RESTMethodDefinition restMethodDef = jsonAgent.get(call.getMethodURI()); assert null != restMethodDef : "Undefined controller method for URI [" + command.getUri() + "/" + call.getMethodURI() + "]"; WeakReference<Object> wkRef = null; if (null != restMethodDef.getBeanParameterType()) wkRef = new WeakReference<Object>( restMethodDef.invoke(getBeanParameter(command, restMethodDef.getBeanParameterType()))); else/*from www . ja v a 2 s .c o m*/ wkRef = new WeakReference<Object>(restMethodDef.invoke((Object[]) null)); AbstractHttpEntity entity = null; if (null != wkRef && null != wkRef.get()) if (getObjectMapperService().canSerialize(wkRef.get().getClass())) { debug("Handled URI [{}] with controller [{}] and result [{}]", command.getUri(), jsonAgent, wkRef.get()); final WeakReference<ByteArrayOutputStream> os = new WeakReference<ByteArrayOutputStream>( new ByteArrayOutputStream()); getObjectMapperService().writeValue(os.get(), wkRef.get()); entity = new InputStreamEntity(new ByteArrayInputStream(os.get().toByteArray()), APPLICATION_JSON_CONTENT_TYPE); } else warn("Object [{}] not JSON serializable!", wkRef.get()); else warn("JSON Controller returned null for expected result of type [{}]", restMethodDef.getBeanParameterType()); command.getResponse().setStatusCode(HttpStatus.SC_OK); if (null == entity) entity = new StringEntity(EMPTY_JSON_OBJECT, APPLICATION_JSON_CONTENT_TYPE); command.getResponse().setEntity(entity); }
From source file:com.phonegap.plugins.CloudStorage.java
/** * Executes the request and returns PluginResult. *//ww w . java 2s. co m * @param action The action to execute. * @param data JSONArry of arguments for the plugin. * 'url': server url for upload * 'file URI': URI of file to upload * 'X-Auth-Token': authentication header to use for this request * @param callbackId The callback id used when calling back into JavaScript. * @return A PluginResult object with a status and message. * */ public PluginResult execute(String action, JSONArray data, String callbackId) { PluginResult result = null; if (ACTION_UPLOAD.equals(action) || ACTION_STORE.equals(action)) { try { String serverUrl = data.get(0).toString(); String imageURI = data.getString(1).toString(); String token = null; if (ACTION_UPLOAD.equals(action)) { token = data.getString(2).toString(); } File file = new File(new URI(imageURI)); try { HttpClient httpclient = new DefaultHttpClient(); HttpPut httpput = new HttpPut(serverUrl); InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1); if (ACTION_UPLOAD.equals(action)) { reqEntity.setContentType("binary/octet-stream"); reqEntity.setChunked(true); // Send in multiple parts if needed } else { reqEntity.setContentType("image/jpg"); } httpput.setEntity(reqEntity); if (token != null) { httpput.addHeader("X-Auth-Token", token); } HttpResponse response = httpclient.execute(httpput); Log.d(LOG_TAG, "http response: " + response.getStatusLine().getStatusCode() + response.getStatusLine().getReasonPhrase()); //Do something with response... result = new PluginResult(Status.OK, response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(LOG_TAG, e.getLocalizedMessage()); result = new PluginResult(Status.ERROR); } } catch (JSONException e) { Log.d(LOG_TAG, e.getLocalizedMessage()); result = new PluginResult(Status.JSON_EXCEPTION); } catch (Exception e1) { Log.d(LOG_TAG, e1.getLocalizedMessage()); result = new PluginResult(Status.ERROR); } } return result; }
From source file:com.github.lpezet.antiope.dao.RepeatableInputStreamRequestEntity.java
/** * Creates a new RepeatableInputStreamRequestEntity using the information * from the specified request. If the input stream containing the request's * contents is repeatable, then this RequestEntity will report as being * repeatable./* www.j ava 2 s . c o m*/ * * @param request * The details of the request being written out (content type, * content length, and content). */ public RepeatableInputStreamRequestEntity(final Request<?> request) { setChunked(false); /* * If we don't specify a content length when we instantiate our * InputStreamRequestEntity, then HttpClient will attempt to * buffer the entire stream contents into memory to determine * the content length. * * TODO: It'd be nice to have easier access to content length and * content type from the request, instead of having to look * directly into the headers. */ long contentLength = -1; try { String contentLengthString = request.getHeaders().get("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } } catch (NumberFormatException nfe) { log.warn("Unable to parse content length from request. " + "Buffering contents in memory."); } String contentType = request.getHeaders().get("Content-Type"); /* ThroughputMetricType type = ServiceMetricTypeGuesser .guessThroughputMetricType(request, ServiceMetricType.UPLOAD_THROUGHPUT_NAME_SUFFIX, ServiceMetricType.UPLOAD_BYTE_COUNT_NAME_SUFFIX); */ //if (type == null) { inputStreamRequestEntity = new InputStreamEntity(request.getContent(), contentLength); //} else { // inputStreamRequestEntity = // new MetricInputStreamEntity(type, request.getContent(), contentLength); //} inputStreamRequestEntity.setContentType(contentType); content = request.getContent(); setContent(content); setContentType(contentType); setContentLength(contentLength); }
From source file:com.github.lpezet.antiope2.dao.http.RepeatableInputStreamRequestEntity.java
/** * Creates a new RepeatableInputStreamRequestEntity using the information * from the specified request. If the input stream containing the request's * contents is repeatable, then this RequestEntity will report as being * repeatable.//from w w w . j a va 2 s .c o m * * @param request * The details of the request being written out (content type, * content length, and content). */ public RepeatableInputStreamRequestEntity(final IHttpRequest request) { setChunked(false); /* * If we don't specify a content length when we instantiate our * InputStreamRequestEntity, then HttpClient will attempt to * buffer the entire stream contents into memory to determine * the content length. * * TODO: It'd be nice to have easier access to content length and * content type from the request, instead of having to look * directly into the headers. */ long contentLength = -1; try { String contentLengthString = request.getHeaders().get("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } } catch (NumberFormatException nfe) { log.warn("Unable to parse content length from request. " + "Buffering contents in memory."); } String contentType = request.getHeaders().get("Content-Type"); /* ThroughputMetricType type = ServiceMetricTypeGuesser .guessThroughputMetricType(request, ServiceMetricType.UPLOAD_THROUGHPUT_NAME_SUFFIX, ServiceMetricType.UPLOAD_BYTE_COUNT_NAME_SUFFIX); */ //if (type == null) { inputStreamRequestEntity = new InputStreamEntity(request.getContent(), contentLength); //} else { // inputStreamRequestEntity = // new MetricInputStreamEntity(type, request.getContent(), contentLength); //} inputStreamRequestEntity.setContentType(contentType); content = request.getContent(); setContent(content); setContentType(contentType); setContentLength(contentLength); }
From source file:com.msopentech.odatajclient.engine.communication.request.streamed.ODataStreamedRequestImpl.java
/** * {@inheritDoc }// w w w .ja va 2s . co m */ @Override @SuppressWarnings("unchecked") public T execute() { streamManager = getStreamManager(); ((HttpEntityEnclosingRequestBase) request) .setEntity(new InputStreamEntity(streamManager.getBody(), -65000)); futureWrapper.setWrapped(Configuration.getExecutor().submit(new Callable<HttpResponse>() { @Override public HttpResponse call() throws Exception { return doExecute(); } })); // returns the stream manager object return (T) streamManager; }
From source file:com.woonoz.proxy.servlet.HttpEntityEnclosingRequestHandler.java
private HttpEntity createHttpEntity(HttpServletRequest request) throws FileUploadException, IOException { if (ServletFileUpload.isMultipartContent(request)) { return createMultipartEntity(request); } else {//from www . j a va 2 s . co m return new BufferedHttpEntity( new InputStreamEntity(request.getInputStream(), request.getContentLength())); } }
From source file:org.red5.client.net.rtmpt.RTMPTClientConnector.java
public void run() { HttpPost post = null;//from w w w . j a v a 2 s .c om try { RTMPTClientConnection connection = openConnection(); while (!connection.isClosing() && !stopRequested) { IoBuffer toSend = connection.getPendingMessages(SEND_TARGET_SIZE); int limit = toSend != null ? toSend.limit() : 0; if (limit > 0) { post = makePost("send"); post.setEntity(new InputStreamEntity(toSend.asInputStream(), limit)); post.addHeader("Content-Type", CONTENT_TYPE); } else { post = makePost("idle"); post.setEntity(ZERO_REQUEST_ENTITY); } // execute HttpResponse response = httpClient.execute(targetHost, post); // check for error checkResponseCode(response); // handle data byte[] received = EntityUtils.toByteArray(response.getEntity()); IoBuffer data = IoBuffer.wrap(received); if (data.limit() > 0) { data.skip(1); // XXX: polling interval lies in this byte } List<?> messages = connection.decode(data); if (messages == null || messages.isEmpty()) { try { // XXX handle polling delay Thread.sleep(250); } catch (InterruptedException e) { if (stopRequested) { post.abort(); break; } } continue; } IoSession session = new DummySession(); session.setAttribute(RTMPConnection.RTMP_CONNECTION_KEY, connection); session.setAttribute(ProtocolState.SESSION_KEY, connection.getState()); for (Object message : messages) { try { client.messageReceived(message, session); } catch (Exception e) { log.error("Could not process message.", e); } } } finalizeConnection(); client.connectionClosed(connection, connection.getState()); } catch (Throwable e) { log.debug("RTMPT handling exception", e); client.handleException(e); if (post != null) { post.abort(); } } }
From source file:com.web.server.ProxyServlet.java
@Override @SuppressWarnings("unchecked") protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Create new client to perform the proxied request HttpClient httpclient = new DefaultHttpClient(); // Determine final URL StringBuffer uri = new StringBuffer(); uri.append(targetServer);//from w ww .java 2s. co m uri.append(req.getRequestURI()); // Add any supplied query strings String queryString = req.getQueryString(); if (queryString != null) { uri.append("?" + queryString); } // Get HTTP method final String method = req.getMethod(); // Create new HTTP request container HttpRequestBase request = null; // Get content length int contentLength = req.getContentLength(); // Unknown content length ... // if (contentLength == -1) // throw new ServletException("Cannot handle unknown content length"); // If we don't have an entity body, things are quite simple if (contentLength < 1) { request = new HttpRequestBase() { public String getMethod() { return method; } }; } else { // Prepare request HttpEntityEnclosingRequestBase tmpRequest = new HttpEntityEnclosingRequestBase() { public String getMethod() { return method; } }; // Transfer entity body from the received request to the new request InputStreamEntity entity = new InputStreamEntity(req.getInputStream(), contentLength); tmpRequest.setEntity(entity); request = tmpRequest; } // Set URI try { request.setURI(new URI(uri.toString())); } catch (URISyntaxException e) { throw new ServletException("URISyntaxException: " + e.getMessage()); } // Copy headers from old request to new request // @todo not sure how this handles multiple headers with the same name Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { String headerName = headers.nextElement(); String headerValue = req.getHeader(headerName); // Skip Content-Length and Host String lowerHeader = headerName.toLowerCase(); if (lowerHeader.equals("content-length") == false && lowerHeader.equals("host") == false) { // System.out.println(headerName.toLowerCase() + ": " + headerValue); request.addHeader(headerName, headerValue); } } // Execute the request HttpResponse response = httpclient.execute(request); // Transfer status code to the response StatusLine status = response.getStatusLine(); resp.setStatus(status.getStatusCode()); // resp.setStatus(status.getStatusCode(), status.getReasonPhrase()); // This seems to be deprecated. Yes status message is "ambigous", but I don't approve // Transfer headers to the response Header[] responseHeaders = response.getAllHeaders(); for (int i = 0; i < responseHeaders.length; i++) { Header header = responseHeaders[i]; resp.addHeader(header.getName(), header.getValue()); } // Transfer proxy response entity to the servlet response HttpEntity entity = response.getEntity(); InputStream input = entity.getContent(); OutputStream output = resp.getOutputStream(); int b = input.read(); while (b != -1) { output.write(b); b = input.read(); } // Clean up input.close(); output.close(); httpclient.getConnectionManager().shutdown(); }
From source file:cn.ctyun.amazonaws.http.RepeatableInputStreamRequestEntity.java
/** * Creates a new RepeatableInputStreamRequestEntity using the information * from the specified request. If the input stream containing the request's * contents is repeatable, then this RequestEntity will report as being * repeatable./* w w w .ja v a 2 s. com*/ * * @param request * The details of the request being written out (content type, * content length, and content). */ RepeatableInputStreamRequestEntity(Request<?> request) { setChunked(false); /* * If we don't specify a content length when we instantiate our * InputStreamRequestEntity, then HttpClient will attempt to * buffer the entire stream contents into memory to determine * the content length. * * TODO: It'd be nice to have easier access to content length and * content type from the request, instead of having to look * directly into the headers. */ long contentLength = -1; try { String contentLengthString = request.getHeaders().get("Content-Length"); if (contentLengthString != null) { contentLength = Long.parseLong(contentLengthString); } } catch (NumberFormatException nfe) { log.warn("Unable to parse content length from request. " + "Buffering contents in memory."); } String contentType = request.getHeaders().get("Content-Type"); inputStreamRequestEntity = new InputStreamEntity(request.getContent(), contentLength); inputStreamRequestEntity.setContentType(contentType); content = request.getContent(); setContent(content); setContentType(contentType); setContentLength(contentLength); }