List of usage examples for org.apache.http.message BasicHttpEntityEnclosingRequest BasicHttpEntityEnclosingRequest
public BasicHttpEntityEnclosingRequest(String str, String str2)
From source file:io.hops.hopsworks.api.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); }/* w w w .j a v a 2 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()); } HttpHost httpHost = getTargetHost(servletRequest); proxyResponse = proxyClient.execute(httpHost, 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:com.cisco.oss.foundation.http.apache.ApacheHttpClient.java
private org.apache.http.HttpRequest buildHttpUriRequest(HttpRequest request, Joiner joiner, URI requestUri) { org.apache.http.HttpRequest httpRequest; if (autoEncodeUri) { switch (request.getHttpMethod()) { case GET: httpRequest = new HttpGet(requestUri); break; case POST: httpRequest = new HttpPost(requestUri); break; case PUT: httpRequest = new HttpPut(requestUri); break; case DELETE: httpRequest = new HttpDelete(requestUri); break; case HEAD: httpRequest = new HttpHead(requestUri); break; case OPTIONS: httpRequest = new HttpOptions(requestUri); break; case PATCH: httpRequest = new HttpPatch(requestUri); break; default:/*from ww w .j av a 2 s . c o m*/ throw new ClientException("You have to one of the REST verbs such as GET, POST etc."); } } else { switch (request.getHttpMethod()) { case POST: case PUT: case DELETE: case PATCH: httpRequest = new BasicHttpEntityEnclosingRequest(request.getHttpMethod().method(), requestUri.toString()); break; default: httpRequest = new BasicHttpRequest(request.getHttpMethod().method(), requestUri.toString()); } } byte[] entity = request.getEntity(); if (entity != null) { if (httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest; httpEntityEnclosingRequestBase .setEntity(new ByteArrayEntity(entity, ContentType.create(request.getContentType()))); } else { throw new ClientException( "sending content for request type " + request.getHttpMethod() + " is not supported!"); } } else { if (request instanceof ApacheHttpRequest && httpRequest instanceof HttpEntityEnclosingRequest) { HttpEntityEnclosingRequest httpEntityEnclosingRequestBase = (HttpEntityEnclosingRequest) httpRequest; ApacheHttpRequest apacheHttpRequest = (ApacheHttpRequest) request; httpEntityEnclosingRequestBase.setEntity(apacheHttpRequest.getApacheHttpEntity()); } } Map<String, Collection<String>> headers = request.getHeaders(); for (Map.Entry<String, Collection<String>> stringCollectionEntry : headers.entrySet()) { String key = stringCollectionEntry.getKey(); Collection<String> stringCollection = stringCollectionEntry.getValue(); String value = joiner.join(stringCollection); httpRequest.setHeader(key, value); } return httpRequest; }
From source file:com.android.unit_tests.TestHttpService.java
/** * This test case executes a series of simple POST requests with chunk * coded content content. //from w w w . j a v a 2 s .com */ @LargeTest public void testSimpleHttpPostsChunked() throws Exception { int reqNo = 20; Random rnd = new Random(); // Prepare some random data List testData = new ArrayList(reqNo); for (int i = 0; i < reqNo; i++) { int size = rnd.nextInt(20000); byte[] data = new byte[size]; rnd.nextBytes(data); testData.add(data); } // Initialize the server-side request handler this.server.registerHandler("*", new HttpRequestHandler() { public void handle(final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity incoming = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] data = EntityUtils.toByteArray(incoming); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); response.setEntity(outgoing); } else { StringEntity outgoing = new StringEntity("No content"); response.setEntity(outgoing); } } }); this.server.start(); DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); HttpHost host = new HttpHost("localhost", this.server.getPort()); try { for (int r = 0; r < reqNo; r++) { if (!conn.isOpen()) { Socket socket = new Socket(host.getHostName(), host.getPort()); conn.bind(socket, this.client.getParams()); } BasicHttpEntityEnclosingRequest post = new BasicHttpEntityEnclosingRequest("POST", "/"); byte[] data = (byte[]) testData.get(r); ByteArrayEntity outgoing = new ByteArrayEntity(data); outgoing.setChunked(true); post.setEntity(outgoing); HttpResponse response = this.client.execute(post, host, conn); byte[] received = EntityUtils.toByteArray(response.getEntity()); byte[] expected = (byte[]) testData.get(r); assertEquals(expected.length, received.length); for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], received[i]); } if (!this.client.keepAlive(response)) { conn.close(); } } //Verify the connection metrics HttpConnectionMetrics cm = conn.getMetrics(); assertEquals(reqNo, cm.getRequestCount()); assertEquals(reqNo, cm.getResponseCount()); } finally { conn.close(); this.server.shutdown(); } }
From source file:org.openqa.grid.internal.utils.SelfRegisteringRemote.java
/** * uses the hub API to get some of its configuration. * @param parameters list of the parameter to be retrieved from the hub * @return/*w w w . j a v a2 s . c o m*/ * @throws Exception */ private JSONObject getHubConfiguration(String... parameters) throws Exception { String hubApi = "http://" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_HOST) + ":" + nodeConfig.getConfiguration().get(RegistrationRequest.HUB_PORT) + "/grid/api/hub"; HttpClient client = httpClientFactory.getHttpClient(); URL api = new URL(hubApi); HttpHost host = new HttpHost(api.getHost(), api.getPort()); String url = api.toExternalForm(); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("GET", url); JSONObject j = new JSONObject(); JSONArray keys = new JSONArray(); j.put("configuration", keys); r.setEntity(new StringEntity(j.toString())); HttpResponse response = client.execute(host, r); return extractObject(response); }
From source file:com.msopentech.thali.relay.RelayWebServer.java
private BasicHttpEntityEnclosingRequest buildRelayRequest(Method method, String path, String query, Map<String, String> headers, byte[] body) throws UnsupportedEncodingException, URISyntaxException { HttpKeyURL baseUrl = new HttpKeyURL(httpKeyTypes.getLocalMachineIPHttpKeyURL()); // When NanoHTTPD decodes the incoming URL in the session object it breaks the URL into three parts. // There is the path which is URL decoded before being handed over. // There is the query string which is NOT URL decoded before being handed over. // And there are the params which are the query parameters of the URL broken out and decoded // To make sure encoding is handled correctly we have chosen to use the URI class to create the // base and provide the URL decoded path. We then manually append the query parameter which is already // encoded. The reason for taking this approach is that it supports wacky query strings that don't // encode correctly or have other strange behavior. String fullHttpsUrl = new URI("https", null, baseUrl.getHost(), baseUrl.getPort(), path, null, null) .toString() + ((query == null || query.isEmpty()) ? "" : "?" + query); BasicHttpEntityEnclosingRequest basicHttpRequest = new BasicHttpEntityEnclosingRequest(method.name(), fullHttpsUrl);//from w w w. j a va2 s. com // Copy headers from incoming request to new relay request for (Map.Entry<String, String> entry : headers.entrySet()) { // Skip content-length, the library does this automatically if (!entry.getKey().equals("content-length")) { basicHttpRequest.setHeader(entry.getKey(), entry.getValue()); } } // Copy data from source request to new relay request if (body != null && body.length > 0) { ByteArrayEntity bodyEntity = new ByteArrayEntity(body); basicHttpRequest.setEntity(bodyEntity); } return basicHttpRequest; }
From source file:org.openqa.grid.internal.StatusServletTests.java
@Test public void testHubGetNewSessionRequestCount() throws JSONException, IOException { HttpClient client = httpClientFactory.getHttpClient(); String url = hubApi.toExternalForm(); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("GET", url); JSONObject j = new JSONObject(); JSONArray keys = new JSONArray(); keys.put("newSessionRequestCount"); j.put("configuration", keys); r.setEntity(new StringEntity(j.toString())); HttpResponse response = client.execute(host, r); assertEquals(200, response.getStatusLine().getStatusCode()); JSONObject o = extractObject(response); assertTrue(o.getBoolean("success")); assertEquals(0, o.getInt("newSessionRequestCount")); }
From source file:com.google.gwt.jolokia.server.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); }/*from w w w . ja v a 2s. co 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); //debugProxyRequest(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.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java
protected HttpRequest buildHttpRequest(String verb, String uri, InputStreamEntity entity, MultiValueMap<String, String> headers, MultiValueMap<String, String> params) { HttpRequest httpRequest;//from w ww .j av a 2 s . c o m switch (verb.toUpperCase()) { case "POST": HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params)); httpRequest = httpPost; httpPost.setEntity(entity); break; case "PUT": HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params)); httpRequest = httpPut; httpPut.setEntity(entity); break; case "PATCH": HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params)); httpRequest = httpPatch; httpPatch.setEntity(entity); break; case "DELETE": BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(verb, uri + this.helper.getQueryString(params)); httpRequest = entityRequest; entityRequest.setEntity(entity); break; default: httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params)); log.debug(uri + this.helper.getQueryString(params)); } httpRequest.setHeaders(convertHeaders(headers)); return httpRequest; }
From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java
public void postAndRecieve(String method, String URL, ArrayList<BasicHeader> headers, String body, boolean authenticate) throws IOException { BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(method, URL); BasicHeader head = null;//w w w . j a v a2 s. com BasicHeader h2 = null; if (authenticate) { head = new BasicHeader("ID", server.getLogin()); h2 = new BasicHeader("Password", server.getPassword()); } BasicHttpEntity entity = new BasicHttpEntity(); if (body != null) { InputStream in = null; Log.i("Android Mobile Voting", "loading entity"); try { in = new ByteArrayInputStream(body.getBytes("UTF-8")); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } entity.setContent(in); request.setEntity(entity); } request.addHeader(head); request.addHeader(h2); if (headers != null) { } HttpHost g = new HttpHost(server.getAddress(), port, usingScheme); connection.execute(g, request); Log.e("Android Mobile Voting", "sending"); }
From source file:org.openqa.grid.internal.StatusServletTests.java
@Test public void testHubGetSlotCounts() throws JSONException, IOException { HttpClient client = httpClientFactory.getHttpClient(); String url = hubApi.toExternalForm(); BasicHttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest("GET", url); JSONObject j = new JSONObject(); JSONArray keys = new JSONArray(); keys.put("slotCounts"); j.put("configuration", keys); r.setEntity(new StringEntity(j.toString())); HttpResponse response = client.execute(host, r); assertEquals(200, response.getStatusLine().getStatusCode()); JSONObject o = extractObject(response); assertTrue(o.getBoolean("success")); JSONObject slotCounts = o.getJSONObject("slotCounts"); assertNotNull(slotCounts);//from www . j a v a 2 s .c o m assertEquals(4, slotCounts.getInt("free")); assertEquals(5, slotCounts.getInt("total")); }