List of usage examples for org.apache.http.entity InputStreamEntity InputStreamEntity
public InputStreamEntity(InputStream inputStream, ContentType contentType)
From source file:com.klarna.checkout.stubs.HttpClientStub.java
/** * Stubbed Execute implementation./* ww w . j a v a2 s. c o m*/ * * @param <T> The class ResponseHandler operates on * @param hur HttpUriRequest object * @param rh ResponseHandler object * @param hc HttpContext holder * * @return ResponseHandler result * * @throws IOException never */ @Override public <T> T execute(final HttpUriRequest hur, final ResponseHandler<? extends T> rh, final HttpContext hc) throws IOException { this.httpUriReq = hur; List<Integer> redirects = new ArrayList(); redirects.add(301); redirects.add(302); redirects.add(303); this.visited.clear(); if (this.httpUriReq instanceof HttpEntityEnclosingRequest) { try { this.httpUriReq = new EntityEnclosingRequestWrapper((HttpEntityEnclosingRequest) hur); } catch (ProtocolException ex) { throw new IOException(ex); } } int status; do { try { for (HttpRequestInterceptor hri : requestInterceptors) { hri.process(this.httpUriReq, hc); } } catch (HttpException ex) { throw new ClientProtocolException(ex); } if (!this.visited.add(this.httpUriReq.getURI())) { throw new ClientProtocolException(new CircularRedirectException()); } this.lastResponse = this.getResponse(); if (this.lastResponse.getStatusLine().getStatusCode() < 400) { fixData(); } try { for (HttpResponseInterceptor hri : responseInterceptors) { hri.process(this.lastResponse, hc); } } catch (HttpException ex) { throw new ClientProtocolException(ex); } status = this.lastResponse.getStatusLine().getStatusCode(); Header location = this.lastResponse.getLastHeader("Location"); if (location != null) { this.httpUriReq = new HttpGet(location.getValue()); } } while (redirects.contains(status)); if (this.data.containsKey("test")) { ByteArrayInputStream bis = new ByteArrayInputStream(JSONObject.toJSONString(data).getBytes()); this.lastResponse.setEntity(new InputStreamEntity(bis, bis.available())); } return rh.handleResponse(this.lastResponse); }
From source file:org.red5.client.net.remoting.DSRemotingClient.java
/** * Invoke a method synchronously on the remoting server. * // w ww. ja v a 2 s. c o m * @param method Method name * @param params Parameters passed to method * @return the result of the method call */ @Override public Object invokeMethod(String method, Object[] params) { log.debug("invokeMethod url: {}", (url + appendToUrl)); IoBuffer resultBuffer = null; IoBuffer data = encodeInvoke(method, params); //setup POST HttpPost post = null; try { post = new HttpPost(url + appendToUrl); post.addHeader("Content-Type", CONTENT_TYPE); post.setEntity(new InputStreamEntity(data.asInputStream(), data.limit())); // execute the method HttpResponse response = client.execute(post); int code = response.getStatusLine().getStatusCode(); log.debug("HTTP response code: {}", code); if (code / 100 != 2) { throw new RuntimeException("Didn't receive success from remoting server"); } else { HttpEntity entity = response.getEntity(); if (entity != null) { //fix for Trac #676 int contentLength = (int) entity.getContentLength(); //default the content length to 16 if post doesn't contain a good value if (contentLength < 1) { contentLength = 16; } // get the response as bytes byte[] bytes = EntityUtils.toByteArray(entity); resultBuffer = IoBuffer.wrap(bytes); resultBuffer.flip(); Object result = decodeResult(resultBuffer); if (result instanceof RecordSet) { // Make sure we can retrieve paged results ((RecordSet) result).setRemotingClient(this); } return result; } } } catch (Exception ex) { log.error("Error while invoking remoting method.", ex); post.abort(); } finally { if (resultBuffer != null) { resultBuffer.free(); resultBuffer = null; } data.free(); data = null; } return null; }
From source file:org.modeshape.web.jcr.rest.AbstractRestTest.java
private <T extends HttpRequestBase> T newRequest(Class<T> clazz, InputStream inputStream, String contentType, String accepts, String... pathSegments) { String url = RestHelper.urlFrom(getServerContext(), pathSegments); try {//from ww w . j a v a 2 s . c o m URIBuilder uriBuilder; try { uriBuilder = new URIBuilder(url); } catch (URISyntaxException e) { uriBuilder = new URIBuilder(URL_ENCODER.encode(url)); } T result = clazz.getConstructor(URI.class).newInstance(uriBuilder.build()); result.setHeader("Accept", accepts); result.setHeader("Content-Type", contentType); if (inputStream != null) { assertTrue("Invalid request clazz (requires an entity)", result instanceof HttpEntityEnclosingRequestBase); InputStreamEntity inputStreamEntity = new InputStreamEntity(inputStream, inputStream.available()); ((HttpEntityEnclosingRequestBase) result).setEntity(new BufferedHttpEntity(inputStreamEntity)); } return result; } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); return null; } }
From source file:iristk.speech.nuancecloud.JSpeexNuanceCloudRecognizerListener.java
private void initRequest() { try {/*w ww .j av a2 s . c o m*/ byteQueue.reset(); encodedQueue.reset(); JSpeexEnc encoder = new JSpeexEnc(16000); encoder.startEncoding(byteQueue, encodedQueue); List<NameValuePair> qparams = new ArrayList<NameValuePair>(); qparams.add(new BasicNameValuePair("appId", APP_ID)); qparams.add(new BasicNameValuePair("appKey", APP_KEY)); qparams.add(new BasicNameValuePair("id", DEVICE_ID)); URI uri = URIUtils.createURI("https", HOSTNAME, 443, SERVLET, URLEncodedUtils.format(qparams, "UTF-8"), null); final HttpPost httppost = new HttpPost(uri); httppost.addHeader("Content-Type", CODEC); httppost.addHeader("Content-Language", LANGUAGE); httppost.addHeader("Accept-Language", LANGUAGE); httppost.addHeader("Accept", RESULTS_FORMAT); httppost.addHeader("Accept-Topic", LM); if (nuanceAudioSource != null) { httppost.addHeader("X-Dictation-AudioSource", nuanceAudioSource.name()); } if (cookie != null) httppost.addHeader("Cookie", cookie); InputStreamEntity reqEntity = new InputStreamEntity(encodedQueue.getInputStream(), -1); reqEntity.setContentType(CODEC); httppost.setEntity(reqEntity); postThread = new PostThread(httppost); } catch (URISyntaxException e) { e.printStackTrace(); } }
From source file:com.reachcall.pretty.http.ProxyServlet.java
@SuppressWarnings("unchecked") private void doPost(HttpPost method, HttpServletRequest req) throws IOException { copyHeaders(req, method);/*from w w w . j a va 2 s. c o m*/ if (CONTENT_TYPE_FORM.equalsIgnoreCase(req.getContentType())) { Map<String, String[]> params = (Map<String, String[]>) req.getParameterMap(); List<NameValuePair> pairs = new LinkedList<NameValuePair>(); for (String name : params.keySet()) { String[] values = params.get(name); for (String value : values) { NameValuePair pair = new BasicNameValuePair(name, value); pairs.add(pair); } } method.setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); } else { method.setEntity(new InputStreamEntity(req.getInputStream(), req.getContentLength())); } }
From source file:com.nesscomputing.httpclient.factory.httpclient4.ApacheHttpClient4Factory.java
@Override public HttpClientBodySource getHttpBodySourceFor(final Object content) { checkRunning();/*ww w. j a v a2s . c om*/ if (content == null) { LOG.debug("No content given, returning null"); return null; } if (content instanceof String) { LOG.debug("Returning String based body source."); return new InternalHttpBodySource(new BetterStringEntity(String.class.cast(content), Charsets.UTF_8)); } else if (content instanceof byte[]) { LOG.debug("Returning byte array based body source."); return new InternalHttpBodySource(new ByteArrayEntity((byte[]) content)); } else if (content instanceof InputStream) { LOG.debug("Returning InputStream based body source."); return new InternalHttpBodySource(new InputStreamEntity((InputStream) content, -1)); } return null; }
From source file:io.hops.kibana.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { //initialize request attributes from caches if unset by a subclass by this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); }/*www. j a v a2s. c o m*/ if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // 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; //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); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(getTargetHost(servletRequest), 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, servletRequest, 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; //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:org.apache.manifoldcf.agents.output.solr.ModifiedHttpSolrServer.java
@Override public NamedList<Object> request(final SolrRequest request, final ResponseParser processor) throws SolrServerException, IOException { HttpRequestBase method = null;//w w w . j ava 2s . c om InputStream is = null; SolrParams params = request.getParams(); Collection<ContentStream> streams = requestWriter.getContentStreams(request); String path = requestWriter.getPath(request); if (path == null || !path.startsWith("/")) { path = DEFAULT_PATH; } ResponseParser parser = request.getResponseParser(); if (parser == null) { parser = this.parser; } // The parser 'wt=' and 'version=' params are used instead of the original // params ModifiableSolrParams wparams = new ModifiableSolrParams(params); if (parser != null) { wparams.set(CommonParams.WT, parser.getWriterType()); wparams.set(CommonParams.VERSION, parser.getVersion()); } if (invariantParams != null) { wparams.add(invariantParams); } params = wparams; int tries = maxRetries + 1; try { while (tries-- > 0) { // Note: since we aren't do intermittent time keeping // ourselves, the potential non-timeout latency could be as // much as tries-times (plus scheduling effects) the given // timeAllowed. try { if (SolrRequest.METHOD.GET == request.getMethod()) { if (streams != null) { throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!"); } method = new HttpGet(baseUrl + path + toQueryString(params, false)); } else if (SolrRequest.METHOD.POST == request.getMethod()) { String url = baseUrl + path; boolean hasNullStreamName = false; if (streams != null) { for (ContentStream cs : streams) { if (cs.getName() == null) { hasNullStreamName = true; break; } } } boolean isMultipart = (this.useMultiPartPost || (streams != null && streams.size() > 1)) && !hasNullStreamName; LinkedList<NameValuePair> postParams = new LinkedList<NameValuePair>(); if (streams == null || isMultipart) { HttpPost post = new HttpPost(url); post.setHeader("Content-Charset", "UTF-8"); if (!isMultipart) { post.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); } List<FormBodyPart> parts = new LinkedList<FormBodyPart>(); Iterator<String> iter = params.getParameterNamesIterator(); while (iter.hasNext()) { String p = iter.next(); String[] vals = params.getParams(p); if (vals != null) { for (String v : vals) { if (isMultipart) { parts.add( new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8))); } else { postParams.add(new BasicNameValuePair(p, v)); } } } } if (isMultipart && streams != null) { for (ContentStream content : streams) { String contentType = content.getContentType(); if (contentType == null) { contentType = "application/octet-stream"; // default } String contentName = content.getName(); parts.add(new FormBodyPart(contentName, new InputStreamBody(content.getStream(), contentType, content.getName()))); } } if (parts.size() > 0) { ModifiedMultipartEntity entity = new ModifiedMultipartEntity( HttpMultipartMode.STRICT, null, StandardCharsets.UTF_8); for (FormBodyPart p : parts) { entity.addPart(p); } post.setEntity(entity); } else { //not using multipart post.setEntity(new UrlEncodedFormEntity(postParams, StandardCharsets.UTF_8)); } method = post; } // It is has one stream, it is the post body, put the params in the URL else { String pstr = toQueryString(params, false); HttpPost post = new HttpPost(url + pstr); // Single stream as body // Using a loop just to get the first one final ContentStream[] contentStream = new ContentStream[1]; for (ContentStream content : streams) { contentStream[0] = content; break; } if (contentStream[0] instanceof RequestWriter.LazyContentStream) { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } else { post.setEntity(new InputStreamEntity(contentStream[0].getStream(), -1) { @Override public Header getContentType() { return new BasicHeader("Content-Type", contentStream[0].getContentType()); } @Override public boolean isRepeatable() { return false; } }); } method = post; } } else { throw new SolrServerException("Unsupported method: " + request.getMethod()); } } catch (NoHttpResponseException r) { method = null; if (is != null) { is.close(); } // If out of tries then just rethrow (as normal error). if (tries < 1) { throw r; } } } } catch (IOException ex) { throw new SolrServerException("error reading streams", ex); } // XXX client already has this set, is this needed? //method.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, // followRedirects); method.addHeader("User-Agent", AGENT); InputStream respBody = null; boolean shouldClose = true; try { // Execute the method. final HttpResponse response = httpClient.execute(method); int httpStatus = response.getStatusLine().getStatusCode(); // Read the contents respBody = response.getEntity().getContent(); // handle some http level checks before trying to parse the response switch (httpStatus) { case HttpStatus.SC_OK: case HttpStatus.SC_BAD_REQUEST: case HttpStatus.SC_CONFLICT: // 409 break; case HttpStatus.SC_MOVED_PERMANENTLY: case HttpStatus.SC_MOVED_TEMPORARILY: if (!followRedirects) { throw new SolrServerException( "Server at " + getBaseURL() + " sent back a redirect (" + httpStatus + ")."); } break; default: throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), "Server at " + getBaseURL() + " returned non ok status:" + httpStatus + ", message:" + response.getStatusLine().getReasonPhrase()); } if (processor == null) { // no processor specified, return raw stream NamedList<Object> rsp = new NamedList<Object>(); rsp.add("stream", respBody); // Only case where stream should not be closed shouldClose = false; return rsp; } Charset charsetObject = ContentType.getOrDefault(response.getEntity()).getCharset(); String charset; if (charsetObject != null) charset = charsetObject.name(); else charset = "utf-8"; NamedList<Object> rsp = processor.processResponse(respBody, charset); if (httpStatus != HttpStatus.SC_OK) { String reason = null; try { NamedList err = (NamedList) rsp.get("error"); if (err != null) { reason = (String) err.get("msg"); // TODO? get the trace? } } catch (Exception ex) { } if (reason == null) { StringBuilder msg = new StringBuilder(); msg.append(response.getStatusLine().getReasonPhrase()); msg.append("\n\n"); msg.append("request: " + method.getURI()); reason = URLDecoder.decode(msg.toString()); } throw new SolrException(SolrException.ErrorCode.getErrorCode(httpStatus), reason); } return rsp; } catch (ConnectException e) { throw new SolrServerException("Server refused connection at: " + getBaseURL(), e); } catch (SocketTimeoutException e) { throw new SolrServerException("Timeout occured while waiting response from server at: " + getBaseURL(), e); } catch (IOException e) { throw new SolrServerException("IOException occured when talking to server at: " + getBaseURL(), e); } finally { if (respBody != null && shouldClose) { try { respBody.close(); } catch (Throwable t) { } // ignore } } }
From source file:org.owasp.appsensor.block.proxy.servlet.ProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { //initialize request attributes from caches if unset by a subclass by this point if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) { servletRequest.setAttribute(ATTR_TARGET_URI, targetUri); }//www .ja v a2 s. c o m if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) { servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost); } // 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; //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); HttpResponse proxyResponse = null; try { // Execute the request if (doLog) { log("proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); } proxyResponse = proxyClient.execute(getTargetHost(servletRequest), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); // copying response headers to make sure SESSIONID or other Cookie which comes from remote server // will be saved in client when the proxied url was redirected to another one. // see issue [#51](https://github.com/mitre/HTTP-Proxy-Servlet/issues/51) copyResponseHeaders(proxyResponse, servletRequest, servletResponse); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode)) { //the response is already "committed" now without any body to send 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()); // 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:com.yahoo.ycsb.webservice.rest.RestClient.java
private int httpExecute(HttpEntityEnclosingRequestBase request, String data) throws IOException { requestTimedout.setIsSatisfied(false); Thread timer = new Thread(new Timer(execTimeout, requestTimedout)); timer.start();//www .ja va 2 s. co m int responseCode = 200; for (int i = 0; i < headers.length; i = i + 2) { request.setHeader(headers[i], headers[i + 1]); } InputStreamEntity reqEntity = new InputStreamEntity(new ByteArrayInputStream(data.getBytes()), ContentType.APPLICATION_FORM_URLENCODED); reqEntity.setChunked(true); request.setEntity(reqEntity); CloseableHttpResponse response = client.execute(request); responseCode = response.getStatusLine().getStatusCode(); HttpEntity responseEntity = response.getEntity(); // If null entity don't bother about connection release. if (responseEntity != null) { InputStream stream = responseEntity.getContent(); if (compressedResponse) { stream = new GZIPInputStream(stream); } BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); StringBuffer responseContent = new StringBuffer(); String line = ""; while ((line = reader.readLine()) != null) { if (requestTimedout.isSatisfied()) { // Must avoid memory leak. reader.close(); stream.close(); EntityUtils.consumeQuietly(responseEntity); response.close(); client.close(); throw new TimeoutException(); } responseContent.append(line); } timer.interrupt(); // Closing the input stream will trigger connection release. stream.close(); } EntityUtils.consumeQuietly(responseEntity); response.close(); client.close(); return responseCode; }