List of usage examples for org.apache.http.message BasicHttpRequest BasicHttpRequest
public BasicHttpRequest(String str, String str2)
From source file:android.net.http.HttpsConnection.java
/** * Opens the connection to a http server or proxy. * * @return the opened low level connection * @throws IOException if the connection fails for any reason. *///w w w.j a v a 2 s .c o m @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { SSLSocket sslSock = null; if (mProxyHost != null) { // If we have a proxy set, we first send a CONNECT request // to the proxy; if the proxy returns 200 OK, we negotiate // a secure connection to the target server via the proxy. // If the request fails, we drop it, but provide the event // handler with the response status and headers. The event // handler is then responsible for cancelling the load or // issueing a new request. AndroidHttpClientConnection proxyConnection = null; Socket proxySock = null; try { proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort()); proxySock.setSoTimeout(60 * 1000); proxyConnection = new AndroidHttpClientConnection(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(params, 8192); proxyConnection.bind(proxySock, params); } catch (IOException e) { if (proxyConnection != null) { proxyConnection.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to establish a connection to the proxy"; } throw new IOException(errorMessage); } StatusLine statusLine = null; int statusCode = 0; Headers headers = new Headers(); try { BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString()); // add all 'proxy' headers from the original request for (Header h : req.mHttpRequest.getAllHeaders()) { String headerName = h.getName().toLowerCase(); if (headerName.startsWith("proxy") || headerName.equals("keep-alive")) { proxyReq.addHeader(h); } } proxyConnection.sendRequestHeader(proxyReq); proxyConnection.flush(); // it is possible to receive informational status // codes prior to receiving actual headers; // all those status codes are smaller than OK 200 // a loop is a standard way of dealing with them do { statusLine = proxyConnection.parseResponseHeader(headers); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); } catch (ParseException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (HttpException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (IOException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } if (statusCode == HttpStatus.SC_OK) { try { sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } else { // if the code is not OK, inform the event handler ProtocolVersion version = statusLine.getProtocolVersion(); req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase()); req.mEventHandler.headers(headers); req.mEventHandler.endData(); proxyConnection.close(); // here, we return null to indicate that the original // request needs to be dropped return null; } } else { // if we do not have a proxy, we simply connect to the host try { sslSock = (SSLSocket) getSocketFactory().createSocket(); sslSock.setSoTimeout(SOCKET_TIMEOUT); sslSock.connect(new InetSocketAddress(mHost.getHostName(), mHost.getPort())); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } // do handshake and validate server certificates SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); EventHandler eventHandler = req.getEventHandler(); // Update the certificate info (to be consistent, it is better to do it // here, before we start handling SSL errors, if any) eventHandler.certificate(mCertificate); // Inform the user if there is a problem if (error != null) { // handleSslErrorRequest may immediately unsuspend if it wants to // allow the certificate anyway. // So we mark the connection as suspended, call handleSslErrorRequest // then check if we're still suspended and only wait if we actually // need to. synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = eventHandler.handleSslErrorRequest(error); if (!canHandle) { throw new IOException("failed to handle " + error); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. sslSock.close(); throw new SSLConnectionClosedByUserException("connection closed by the user"); } } } // All went well, we have an open, verified connection. AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sslSock, params); return conn; }
From source file:android.net.http.HttpsConnection.java
/** * Opens the connection to a http server or proxy. * * @return the opened low level connection * @throws IOException if the connection fails for any reason. *///ww w . j a va 2 s . c o m @Override AndroidHttpClientConnection openConnection(Request req) throws IOException { SSLSocket sslSock = null; if (mProxyHost != null) { // If we have a proxy set, we first send a CONNECT request // to the proxy; if the proxy returns 200 OK, we negotiate // a secure connection to the target server via the proxy. // If the request fails, we drop it, but provide the event // handler with the response status and headers. The event // handler is then responsible for cancelling the load or // issueing a new request. AndroidHttpClientConnection proxyConnection = null; Socket proxySock = null; try { proxySock = new Socket(mProxyHost.getHostName(), mProxyHost.getPort()); proxySock.setSoTimeout(60 * 1000); proxyConnection = new AndroidHttpClientConnection(); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setSocketBufferSize(params, 8192); proxyConnection.bind(proxySock, params); } catch (IOException e) { if (proxyConnection != null) { proxyConnection.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to establish a connection to the proxy"; } throw new IOException(errorMessage); } StatusLine statusLine = null; int statusCode = 0; Headers headers = new Headers(); try { BasicHttpRequest proxyReq = new BasicHttpRequest("CONNECT", mHost.toHostString()); // add all 'proxy' headers from the original request, we also need // to add 'host' header unless we want proxy to answer us with a // 400 Bad Request for (Header h : req.mHttpRequest.getAllHeaders()) { String headerName = h.getName().toLowerCase(Locale.ROOT); if (headerName.startsWith("proxy") || headerName.equals("keep-alive") || headerName.equals("host")) { proxyReq.addHeader(h); } } proxyConnection.sendRequestHeader(proxyReq); proxyConnection.flush(); // it is possible to receive informational status // codes prior to receiving actual headers; // all those status codes are smaller than OK 200 // a loop is a standard way of dealing with them do { statusLine = proxyConnection.parseResponseHeader(headers); statusCode = statusLine.getStatusCode(); } while (statusCode < HttpStatus.SC_OK); } catch (ParseException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (HttpException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } catch (IOException e) { String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to send a CONNECT request"; } throw new IOException(errorMessage); } if (statusCode == HttpStatus.SC_OK) { try { sslSock = (SSLSocket) getSocketFactory().createSocket(proxySock, mHost.getHostName(), mHost.getPort(), true); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } else { // if the code is not OK, inform the event handler ProtocolVersion version = statusLine.getProtocolVersion(); req.mEventHandler.status(version.getMajor(), version.getMinor(), statusCode, statusLine.getReasonPhrase()); req.mEventHandler.headers(headers); req.mEventHandler.endData(); proxyConnection.close(); // here, we return null to indicate that the original // request needs to be dropped return null; } } else { // if we do not have a proxy, we simply connect to the host try { sslSock = (SSLSocket) getSocketFactory().createSocket(mHost.getHostName(), mHost.getPort()); sslSock.setSoTimeout(SOCKET_TIMEOUT); } catch (IOException e) { if (sslSock != null) { sslSock.close(); } String errorMessage = e.getMessage(); if (errorMessage == null) { errorMessage = "failed to create an SSL socket"; } throw new IOException(errorMessage); } } // do handshake and validate server certificates SslError error = CertificateChainValidator.getInstance().doHandshakeAndValidateServerCertificates(this, sslSock, mHost.getHostName()); // Inform the user if there is a problem if (error != null) { // handleSslErrorRequest may immediately unsuspend if it wants to // allow the certificate anyway. // So we mark the connection as suspended, call handleSslErrorRequest // then check if we're still suspended and only wait if we actually // need to. synchronized (mSuspendLock) { mSuspended = true; } // don't hold the lock while calling out to the event handler boolean canHandle = req.getEventHandler().handleSslErrorRequest(error); if (!canHandle) { throw new IOException("failed to handle " + error); } synchronized (mSuspendLock) { if (mSuspended) { try { // Put a limit on how long we are waiting; if the timeout // expires (which should never happen unless you choose // to ignore the SSL error dialog for a very long time), // we wake up the thread and abort the request. This is // to prevent us from stalling the network if things go // very bad. mSuspendLock.wait(10 * 60 * 1000); if (mSuspended) { // mSuspended is true if we have not had a chance to // restart the connection yet (ie, the wait timeout // has expired) mSuspended = false; mAborted = true; if (HttpLog.LOGV) { HttpLog.v("HttpsConnection.openConnection():" + " SSL timeout expired and request was cancelled!!!"); } } } catch (InterruptedException e) { // ignore } } if (mAborted) { // The user decided not to use this unverified connection // so close it immediately. sslSock.close(); throw new SSLConnectionClosedByUserException("connection closed by the user"); } } } // All went well, we have an open, verified connection. AndroidHttpClientConnection conn = new AndroidHttpClientConnection(); BasicHttpParams params = new BasicHttpParams(); params.setIntParameter(HttpConnectionParams.SOCKET_BUFFER_SIZE, 8192); conn.bind(sslSock, params); return conn; }
From source file:org.realityforge.proxy_servlet.AbstractProxyServlet.java
private HttpRequest newProxyRequest(final HttpServletRequest servletRequest, final String proxyRequestUri) throws IOException { final String method = servletRequest.getMethod(); if (null != servletRequest.getHeader(HttpHeaders.CONTENT_LENGTH) || null != servletRequest.getHeader(HttpHeaders.TRANSFER_ENCODING)) { //spec: RFC 2616, sec 4.3: either of these two headers signal that there is a message body. final HttpEntityEnclosingRequest r = new BasicHttpEntityEnclosingRequest(method, proxyRequestUri); r.setEntity(new InputStreamEntity(servletRequest.getInputStream(), servletRequest.getContentLength())); return r; } else {//from w ww . java 2 s .co m return new BasicHttpRequest(method, proxyRequestUri); } }
From source file:io.mapzone.controller.vm.http.HttpRequestForwarder.java
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, URISyntaxException { targetUriObj = new URI(targetUri.get()); targetHost = URIUtils.extractHost(targetUriObj); // Make the Request // note: we won't transfer the protocol version because I'm not sure it would // truly be compatible String method = request.getMethod(); String proxyRequestUri = rewriteUrlFromRequest(request); // spec: RFC 2616, sec 4.3: either of these two headers signal that there is // a message body. if (request.getHeader(HttpHeaders.CONTENT_LENGTH) != null || request.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(request.getInputStream(), request.getContentLength())); proxyRequest = eProxyRequest;/*ww w . j a va 2 s.co m*/ } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(request); setXForwardedForHeader(request); // Execute the request try { active.set(this); log.debug("REQUEST " + "[" + StringUtils.right(Thread.currentThread().getName(), 2) + "] " + method + ": " + request.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = proxyClient.execute(targetHost, proxyRequest); } 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 { active.set(null); } // 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.frontcache.hystrix.FC_BypassCache.java
/** * forward all kind of requests (GET, POST, PUT, ...) * //w w w. ja v a 2 s .com * @param httpclient * @param verb * @param uri * @param request * @param headers * @param params * @param requestEntity * @return * @throws Exception */ private HttpResponse forward(HttpClient httpclient, String verb, String uri, HttpServletRequest request, Map<String, List<String>> headers, InputStream requestEntity) throws Exception { URL host = context.getOriginURL(); HttpHost httpHost = FCUtils.getHttpHost(host); uri = (host.getPath() + uri).replaceAll("/{2,}", "/"); HttpRequest httpRequest; switch (verb.toUpperCase()) { case "POST": HttpPost httpPost = new HttpPost(uri + context.getRequestQueryString()); httpRequest = httpPost; httpPost.setEntity(new InputStreamEntity(requestEntity, request.getContentLength())); break; case "PUT": HttpPut httpPut = new HttpPut(uri + context.getRequestQueryString()); httpRequest = httpPut; httpPut.setEntity(new InputStreamEntity(requestEntity, request.getContentLength())); break; case "PATCH": HttpPatch httpPatch = new HttpPatch(uri + context.getRequestQueryString()); httpRequest = httpPatch; httpPatch.setEntity(new InputStreamEntity(requestEntity, request.getContentLength())); break; default: httpRequest = new BasicHttpRequest(verb, uri + context.getRequestQueryString()); } try { httpRequest.setHeaders(FCUtils.convertHeaders(headers)); Header acceptEncoding = httpRequest.getFirstHeader("accept-encoding"); if (acceptEncoding != null && acceptEncoding.getValue().contains("gzip")) { httpRequest.setHeader("accept-encoding", "gzip"); } HttpResponse originResponse = httpclient.execute(httpHost, httpRequest); return originResponse; } finally { // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources // httpclient.getConnectionManager().shutdown(); } }
From source file:org.apache.karaf.cellar.http.balancer.CellarBalancerProxyServlet.java
@Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { String location = locations.get(new Random().nextInt(locations.size())); URI locationUri = URI.create(location); HttpHost host = URIUtils.extractHost(locationUri); LOGGER.debug("CELLAR HTTP BALANCER: proxying to"); LOGGER.debug("CELLAR HTTP BALANCER: URI: {}", locationUri); LOGGER.debug("CELLAR HTTP BALANCER: Host: {}", host); // 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(); LOGGER.debug("CELLAR HTTP BALANCER: Method: {}", method); String proxyRequestUri = rewriteUrlFromRequest(servletRequest, location); LOGGER.debug("CELLAR HTTP BALANCER: Proxy Request URI: {}", proxyRequestUri); HttpRequest proxyRequest;//from w w w .j a v a 2 s . c om //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); LOGGER.debug("CELLAR HTTP BALANCER: copying request headers"); copyRequestHeaders(servletRequest, proxyRequest, host); LOGGER.debug("CELLAR HTTP BALANCER: set X-Forwarded header"); setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request LOGGER.debug("CELLAR HTTP BALANCER: executing proxy request"); proxyResponse = proxyClient.execute(host, proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); LOGGER.debug("CELLAR HTTP BALANCER: status code: {}", statusCode); // 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) LOGGER.debug("CELLAR HTTP BALANCER: copying response headers"); copyResponseHeaders(proxyResponse, servletRequest, servletResponse); if (doResponseRedirectOrNotModifiedLogic(servletRequest, servletResponse, proxyResponse, statusCode, location)) { //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 LOGGER.debug("CELLAR HTTP BALANCER: set response status code"); servletResponse.setStatus(statusCode, proxyResponse.getStatusLine().getReasonPhrase()); // Send the content to the client LOGGER.debug("CELLAR HTTP BALANCER: copying response entity"); 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:securitydigest.TestDigestScheme.java
public void testDigestAuthenticationWithMultipleRealms() throws Exception { String challenge1 = "Digest realm=\"realm1\", nonce=\"abcde\""; String challenge2 = "Digest realm=\"realm2\", nonce=\"123546\""; Credentials cred = new UsernamePasswordCredentials("username", "password"); Credentials cred2 = new UsernamePasswordCredentials("uname2", "password2"); Header authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge1); HttpRequest request = new BasicHttpRequest("Simple", "/"); AuthScheme authscheme = new DigestScheme(); authscheme.processChallenge(authChallenge); Header authResponse = authscheme.authenticate(cred, request); Map<String, String> table = parseAuthResponse(authResponse); assertEquals("username", table.get("username")); assertEquals("realm1", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("abcde", table.get("nonce")); assertEquals("786f500303eac1478f3c2865e676ed68", table.get("response")); authChallenge = new BasicHeader(AUTH.WWW_AUTH, challenge2); AuthScheme authscheme2 = new DigestScheme(); authscheme2.processChallenge(authChallenge); authResponse = authscheme2.authenticate(cred2, request); table = parseAuthResponse(authResponse); assertEquals("uname2", table.get("username")); assertEquals("realm2", table.get("realm")); assertEquals("/", table.get("uri")); assertEquals("123546", table.get("nonce")); assertEquals("0283edd9ef06a38b378b3b74661391e9", table.get("response")); }
From source file:com.nominanuda.web.http.HttpCoreHelper.java
public HttpRequest createRequest(String method, String url) { if (GET.equals(method)) { return new HttpGet(url); } else if (POST.equals(method)) { return new HttpPost(url); } else if (PUT.equals(method)) { return new HttpPut(url); } else if (Collections.find(method, RFC2616_SPECIAL_METHODS)) { return new BasicHttpRequest(method, url); } else {/* ww w . j ava2s . c o m*/ throw new IllegalArgumentException(method + " method not supported"); } }
From source file:io.hops.hopsworks.api.kibana.KibanaProxyServlet.java
/** * Authorize user to access particular index. * * @param servletRequest//from w ww .j a va 2 s. co m * @param servletResponse * @throws ServletException * @throws IOException */ @Override protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws ServletException, IOException { if (servletRequest.getUserPrincipal() == null) { servletResponse.sendError(401, "User is not logged in"); return; } String email = servletRequest.getUserPrincipal().getName(); if (servletRequest.getParameterMap().containsKey("projectId")) { String projectId = servletRequest.getParameterMap().get("projectId")[0]; try { ProjectDTO projectDTO = projectController.getProjectByID(Integer.parseInt(projectId)); currentProjects.put(email, projectDTO.getProjectName()); } catch (ProjectException ex) { LOG.log(Level.SEVERE, null, ex); servletResponse.sendError(403, "Kibana was not accessed from Hopsworks, no current project information is available."); return; } } //Do not authorize admin if (email.equals(Settings.AGENT_EMAIL)) { super.service(servletRequest, servletResponse); return; } MyRequestWrapper myRequestWrapper = new MyRequestWrapper((HttpServletRequest) servletRequest); KibanaFilter kibanaFilter = null; //Filter requests based on path if (servletRequest.getRequestURI().contains("api/saved_objects")) { kibanaFilter = KibanaFilter.KIBANA_SAVED_OBJECTS_API; } else if (servletRequest.getRequestURI().contains("elasticsearch/*/_search")) { kibanaFilter = KibanaFilter.ELASTICSEARCH_SEARCH; } else if (servletRequest.getRequestURI().contains("legacy_scroll_start") || servletRequest.getRequestURI().contains("settings/defaultIndex")) { return; } //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); } 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(myRequestWrapper.getInputStream(), servletRequest.getContentLength())); proxyRequest = eProxyRequest; } else { proxyRequest = new BasicHttpRequest(method, proxyRequestUri); } copyRequestHeaders(servletRequest, proxyRequest); super.setXForwardedForHeader(servletRequest, proxyRequest); HttpResponse proxyResponse = null; try { // Execute the request LOG.log(Level.FINE, "proxy " + method + " uri: " + servletRequest.getRequestURI() + " -- " + proxyRequest.getRequestLine().getUri()); proxyResponse = super.proxyClient.execute(super.getTargetHost(myRequestWrapper), proxyRequest); // Process the response int statusCode = proxyResponse.getStatusLine().getStatusCode(); if (doResponseRedirectOrNotModifiedLogic(myRequestWrapper, 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, kibanaFilter, email); } 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 } }