List of usage examples for javax.servlet.http HttpServletRequest getHeaders
public Enumeration<String> getHeaders(String name);
Enumeration
of String
objects. From source file:org.mitre.dsmiley.httpproxy.ProxyServlet.java
/** * Copy a request header from the servlet client to the proxy request. This * is easily overwritten to filter out certain headers if desired. *//*from ww w .j a v a 2 s. c o m*/ protected void copyRequestHeader(HttpServletRequest servletRequest, HttpRequest proxyRequest, String headerName) { // Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) return; if (hopByHopHeaders.containsHeader(headerName)) return; if (headerName.equalsIgnoreCase("Authorization")) { return; } else if (headerName.equalsIgnoreCase("User-Agent")) { return; } else if (headerName.equalsIgnoreCase("Accept-Encoding")) { return; } else if (headerName.equalsIgnoreCase("Cache-Control")) { return; } else if (headerName.equalsIgnoreCase("Accept")) { return; } else if (headerName.equalsIgnoreCase("Accept-Language")) { return; } else if (headerName.equalsIgnoreCase("Origin")) { return; } @SuppressWarnings("unchecked") Enumeration<String> headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {// sometimes more than one value String headerValue = headers.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (headerName.equalsIgnoreCase(HttpHeaders.HOST)) { HttpHost host = getTargetHost(servletRequest); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); System.out.println("add request header " + headerName + " with value " + headerValue); } else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { //headerValue = getRealCookie(headerValue); } else { System.out.println("add request header " + headerName + " with value " + headerValue); } System.out.println("Copying request header" + headerName + "headerValue"); proxyRequest.addHeader(headerName, headerValue); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private static String buildCanonicalHeaders(HttpServletRequest request, String[] signedHeaders) { List<String> headers = new ArrayList<>(); for (String header : signedHeaders) { headers.add(header.toLowerCase()); }/*from w ww.ja v a2 s .c o m*/ Collections.sort(headers); List<String> headersWithValues = new ArrayList<>(); for (String header : headers) { List<String> values = new ArrayList<>(); StringBuilder headerWithValue = new StringBuilder(); headerWithValue.append(header); headerWithValue.append(":"); for (String value : Collections.list(request.getHeaders(header))) { value = value.trim(); if (!value.startsWith("\"")) { value = value.replaceAll("\\s+", " "); } values.add(value); } headerWithValue.append(Joiner.on(",").join(values)); headersWithValues.add(headerWithValue.toString()); } return Joiner.on("\n").join(headersWithValues); }
From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java
/** * Retrieves all of the headers from the servlet request and sets them on * the proxy request/*from w w w . j av a 2 s. c o m*/ * * @param httpServletRequest * The request object representing the client's request to the * servlet engine * @param httpMethodProxyRequest * The request that we are about to send to the proxy host */ private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest, ProxyHttpConnector proxyHttpConnector) { Collection<String> removableHeaders = proxyHttpConnector.getRemovableHeadersSet(); // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = GenericUtils.cast(httpServletRequest.getHeaderNames()); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME) || stringHeaderName.equalsIgnoreCase("Cookie") || removableHeaders.contains(stringHeaderName.toLowerCase())) { continue; } // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the // client Enumeration<String> enumerationOfHeaderValues = GenericUtils .cast(httpServletRequest.getHeaders(stringHeaderName)); while (enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = (String) enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME)) { stringHeaderValue = getProxyHostAndPort(proxyHttpConnector); } else if (stringHeaderName.equalsIgnoreCase("Referer")) { stringHeaderValue = stringHeaderValue.replaceFirst("://[^/]*/[^/]*/", "://" + getProxyHostAndPort(proxyHttpConnector) + proxyHttpConnector.getBaseDir() + (proxyHttpConnector.getBaseDir().endsWith("/") ? "" : "/")); } Engine.logEngine.debug( "(ReverseProxyServlet) Forwarding header: " + stringHeaderName + "=" + stringHeaderValue); Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:uk.co.tfd.sm.proxy.ProxyServlet.java
@SuppressWarnings("unchecked") @Override//from www .j a v a 2 s . co m protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { boolean proxyStream = false; if (POST_METHOD.equals(request.getMethod()) || PUT_METHOD.equals(request.getMethod())) { String proxyRequest = request.getHeader(SAKAI_PROXY_REQUEST_BODY); proxyStream = Boolean.parseBoolean(proxyRequest); } String path = request.getPathInfo(); Map<String, Object> config = getConfig(path); if (config == null) { response.sendError(404); return; } if (!proxyStream) { String streamBody = (String) config.get(SAKAI_REQUEST_STREAM_BODY); if (streamBody != null) { proxyStream = Boolean.parseBoolean(streamBody); } } Builder<String, Object> headersBuilder = ImmutableMap.builder(); Builder<String, Object> templateParamsBuilder = ImmutableMap.builder(); for (Enumeration<?> enames = request.getHeaderNames(); enames.hasMoreElements();) { String name = (String) enames.nextElement(); if (HEADER_BLACKLIST.contains(name)) { continue; } if (name.equals(BASIC_USER)) { templateParamsBuilder.put(BASIC_USER, request.getHeader(BASIC_USER)); } else if (name.equals(BASIC_PASSWORD)) { templateParamsBuilder.put(BASIC_USER, request.getHeader(BASIC_USER)); } else if (!name.startsWith(":")) { headersBuilder.put(name, toSimpleString( (String[]) EnumerationUtils.toList(request.getHeaders(name)).toArray(new String[0]))); } } Map<String, Object> headers = headersBuilder.build(); // collect the parameters and store into a mutable map. Map<String, String[]> rpm = request.getParameterMap(); for (Entry<String, String[]> e : rpm.entrySet()) { templateParamsBuilder.put(e.getKey(), toSimpleString(e.getValue())); } Map<String, Object> templateParams = templateParamsBuilder.build(); // we might want to pre-process the headers if (config.containsKey(ProxyPreProcessor.CONFIG_PREPROCESSOR)) { String preprocessorName = (String) config.get(ProxyPreProcessor.CONFIG_PREPROCESSOR); ProxyPreProcessor preprocessor = preProcessors.get(preprocessorName); if (preprocessor != null) { preprocessor.preProcessRequest(request, headers, templateParams); } else { LOGGER.warn("Unable to find pre processor of name {} for node {} ", preprocessorName, path); } } ProxyPostProcessor postProcessor = defaultPostProcessor; // we might want to post-process the headers if (config.containsKey(ProxyPostProcessor.CONFIG_POSTPROCESSOR)) { String postProcessorName = (String) config.get(ProxyPostProcessor.CONFIG_POSTPROCESSOR); if (postProcessors.containsKey(postProcessorName)) postProcessor = postProcessors.get(postProcessorName); if (postProcessor == null) { LOGGER.warn("Unable to find post processor of name {} for node {} ", postProcessorName, path); postProcessor = defaultPostProcessor; } } if (postProcessor instanceof CachingProxyProcessor) { CachingProxyProcessor cachingPostProcessor = (CachingProxyProcessor) postProcessor; if (cachingPostProcessor.sendCached(config, templateParams, response)) { return; } } ProxyResponse proxyResponse = proxyClientService.executeCall(config, headers, templateParams, null, -1, null); try { postProcessor.process(config, templateParams, response, proxyResponse); } finally { proxyResponse.close(); } } catch (IOException e) { throw e; } catch (ProxyClientException e) { response.sendError(500, e.getMessage()); } }
From source file:net.yacy.http.servlets.YaCyDefaultServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String pathInfo;/*from w w w.j a v a 2 s . co m*/ Enumeration<String> reqRanges = null; boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null; if (included) { pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO); if (pathInfo == null) { pathInfo = request.getPathInfo(); } } else { pathInfo = request.getPathInfo(); // Is this a Range request? reqRanges = request.getHeaders(HeaderFramework.RANGE); if (!hasDefinedRange(reqRanges)) { reqRanges = null; } } String pathInContext = pathInfo == null ? "/" : pathInfo; // this is the path of the resource in _resourceBase (= path within htroot respective htDocs) boolean endsWithSlash = pathInContext.endsWith(URIUtil.SLASH); // Find the resource Resource resource = null; try { // Look for a class resource boolean hasClass = false; if (reqRanges == null && !endsWithSlash) { final int p = pathInContext.lastIndexOf('.'); if (p >= 0) { String pathofClass = pathInContext.substring(0, p) + ".class"; Resource classresource = _resourceBase.addPath(pathofClass); // Does a class resource exist? if (classresource != null && classresource.exists() && !classresource.isDirectory()) { hasClass = true; } } } // find resource resource = getResource(pathInContext); if (!hasClass && (resource == null || !resource.exists()) && !pathInContext.contains("..")) { // try to get this in the alternative htDocsPath resource = Resource.newResource(new File(_htDocsPath, pathInContext)); } if (ConcurrentLog.isFine("FILEHANDLER")) { ConcurrentLog.fine("FILEHANDLER", "YaCyDefaultServlet: uri=" + request.getRequestURI() + " resource=" + resource); } // Handle resource if (!hasClass && (resource == null || !resource.exists())) { if (included) { throw new FileNotFoundException("!" + pathInContext); } response.sendError(HttpServletResponse.SC_NOT_FOUND); } else if (!resource.isDirectory()) { if (endsWithSlash && pathInContext.length() > 1) { String q = request.getQueryString(); pathInContext = pathInContext.substring(0, pathInContext.length() - 1); if (q != null && q.length() != 0) { pathInContext += "?" + q; } response.sendRedirect(response .encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(), pathInContext))); } else { if (hasClass) { // this is a YaCy servlet, handle the template handleTemplate(pathInfo, request, response); } else { if (included || passConditionalHeaders(request, response, resource)) { sendData(request, response, included, resource, reqRanges); } } } } else { // resource is directory String welcome; if (!endsWithSlash) { StringBuffer buf = request.getRequestURL(); synchronized (buf) { int param = buf.lastIndexOf(";"); if (param < 0) { buf.append('/'); } else { buf.insert(param, '/'); } String q = request.getQueryString(); if (q != null && q.length() != 0) { buf.append('?'); buf.append(q); } response.setContentLength(0); response.sendRedirect(response.encodeRedirectURL(buf.toString())); } } // else look for a welcome file else if (null != (welcome = getWelcomeFile(pathInContext))) { ConcurrentLog.fine("FILEHANDLER", "welcome={}" + welcome); // Forward to the index RequestDispatcher dispatcher = request.getRequestDispatcher(welcome); if (dispatcher != null) { if (included) { dispatcher.include(request, response); } else { dispatcher.forward(request, response); } } } else { if (included || passConditionalHeaders(request, response, resource)) { sendDirectory(request, response, resource, pathInContext); } } } } catch (IllegalArgumentException e) { ConcurrentLog.logException(e); if (!response.isCommitted()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); } } finally { if (resource != null) { resource.close(); } } }
From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { monitor.fireOnRequest(request, response); if (response.isCommitted()) return;//from w w w .jav a 2 s. c om ExtendedHttpMethod method; HttpServletRequest httpRequest = (HttpServletRequest) request; if (httpRequest.getMethod().equals("GET")) method = new ExtendedGetMethod(); else method = new ExtendedPostMethod(); method.setDecompress(false); // for this create ui server and port, properties. JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project); capturedData.setRequestHost(httpRequest.getServerName()); capturedData.setRequestMethod(httpRequest.getMethod()); capturedData.setRequestHeader(httpRequest); capturedData.setHttpRequestParameters(httpRequest); capturedData.setTargetURL(httpRequest.getRequestURL().toString()); CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream()); // check connection header String connectionHeader = httpRequest.getHeader("Connection"); if (connectionHeader != null) { connectionHeader = connectionHeader.toLowerCase(); if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0) connectionHeader = null; } // copy headers boolean xForwardedFor = false; @SuppressWarnings("unused") long contentLength = -1; Enumeration<?> headerNames = httpRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String hdr = (String) headerNames.nextElement(); String lhdr = hdr.toLowerCase(); if (dontProxyHeaders.contains(lhdr)) continue; if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0) continue; if ("content-length".equals(lhdr)) contentLength = request.getContentLength(); Enumeration<?> vals = httpRequest.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { method.setRequestHeader(lhdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers method.setRequestHeader("Via", "SoapUI Monitor"); if (!xForwardedFor) method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr()); if (method instanceof ExtendedPostMethod) ((ExtendedPostMethod) method) .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType())); HostConfiguration hostConfiguration = new HostConfiguration(); StringBuffer url = new StringBuffer("http://"); url.append(httpRequest.getServerName()); if (httpRequest.getServerPort() != 80) url.append(":" + httpRequest.getServerPort()); if (httpRequest.getServletPath() != null) { url.append(httpRequest.getServletPath()); method.setPath(httpRequest.getServletPath()); if (httpRequest.getQueryString() != null) { url.append("?" + httpRequest.getQueryString()); method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString()); } } hostConfiguration.setHost(new URI(url.toString(), true)); // SoapUI.log("PROXY to:" + url); monitor.fireBeforeProxy(request, response, method, hostConfiguration); if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) { if (httpState == null) httpState = new HttpState(); HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState); } else { HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method); } // wait for transaction to end and store it. capturedData.stopCapture(); capturedData.setRequest(capture.getCapturedData()); capturedData.setRawResponseBody(method.getResponseBody()); capturedData.setResponseHeader(method); capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture)); capturedData.setRawResponseData( getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody())); capturedData.setResponseContent(new String(method.getDecompressedResponseBody())); monitor.fireAfterProxy(request, response, method, capturedData); if (!response.isCommitted()) { StringToStringsMap responseHeaders = capturedData.getResponseHeaders(); // capturedData = null; // copy headers to response HttpServletResponse httpResponse = (HttpServletResponse) response; for (String name : responseHeaders.keySet()) { for (String header : responseHeaders.get(name)) httpResponse.addHeader(name, header); } IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream()); } synchronized (this) { if (checkContentType(method)) { monitor.addMessageExchange(capturedData); } } }
From source file:com.sap.cloudlabs.connectivity.proxy.ProxyServlet.java
/** * Returns the request that points to the backend service defined by the provided * <code>urlToService</code> URL. The headers of the origin request are copied to * the backend request, except of "host" and "content-length". * /* w ww .j a v a 2 s . c o m*/ * @param request * original request to the Web application * @param urlToService * URL to the targeted backend service * @return initialized backend service request * @throws IOException */ private HttpRequestBase getBackendRequest(HttpServletRequest request, String urlToService) throws IOException { String method = request.getMethod(); LOGGER.debug("HTTP method: " + method); HttpRequestBase backendRequest = null; if (HttpPost.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPost post = new HttpPost(urlToService); post.setEntity(entity); backendRequest = post; } else if (HttpGet.METHOD_NAME.equals(method)) { HttpGet get = new HttpGet(urlToService); backendRequest = get; } else if (HttpPut.METHOD_NAME.equals(method)) { ByteArrayOutputStream out = new ByteArrayOutputStream(); pipe(request.getInputStream(), out); ByteArrayEntity entity = new ByteArrayEntity(out.toByteArray()); entity.setContentType(request.getHeader("Content-Type")); HttpPut put = new HttpPut(urlToService); put.setEntity(entity); backendRequest = put; } else if (HttpDelete.METHOD_NAME.equals(method)) { HttpDelete delete = new HttpDelete(urlToService); backendRequest = delete; } // copy headers from Web application request to backend request, while // filtering the blocked headers LOGGER.debug("backend request headers:"); Collection<String> blockedHeaders = mergeLists(securityHandler, Arrays.asList(BLOCKED_REQUEST_HEADERS)); Enumeration<String> setCookieHeaders = request.getHeaders("Cookie"); while (setCookieHeaders.hasMoreElements()) { String cookieHeader = setCookieHeaders.nextElement(); if (blockedHeaders.contains(cookieHeader.toLowerCase())) { String replacedCookie = removeJSessionID(cookieHeader); backendRequest.addHeader("Cookie", replacedCookie); } LOGGER.debug("Cookie header => " + cookieHeader); } for (Enumeration<String> e = request.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement().toString(); if (!blockedHeaders.contains(headerName.toLowerCase())) { backendRequest.addHeader(headerName, request.getHeader(headerName)); LOGGER.debug(" => " + headerName + ": " + request.getHeader(headerName)); } else { LOGGER.debug(" => " + headerName + ": blocked request header"); } } return backendRequest; }
From source file:com.groupon.odo.Proxy.java
/** * Retrieves all of the headers from the servlet request and sets them on * the proxy request/* ww w . j a v a 2s. c om*/ * * @param httpServletRequest The request object representing the client's request to the * servlet engine * @param httpMethodProxyRequest The request that we are about to send to the proxy host */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) throws Exception { String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString()); // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) continue; logger.info("Current header: {}", stringHeaderName); // As per the Java Servlet API 2.5 documentation: // Some headers, such as Accept-Language can be sent by clients // as several headers each with a different value rather than // sending the header as a comma separated list. // Thus, we get an Enumeration of the header values sent by the // client Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName); while (enumerationOfHeaderValues.hasMoreElements()) { String stringHeaderValue = enumerationOfHeaderValues.nextElement(); // In case the proxy host is running multiple virtual servers, // rewrite the Host header to ensure that we get content from // the correct virtual server if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) && requestInformation.get().handle) { String hostValue = getHostHeaderForHost(hostName); if (hostValue != null) { stringHeaderValue = hostValue; } } Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.addRequestHeader(header); } } // bail if we aren't fully handling this request if (!requestInformation.get().handle) { return; } // deal with header overrides for the request processRequestHeaderOverrides(httpMethodProxyRequest); }
From source file:ch.unifr.pai.twice.widgets.mpproxy.server.JettyProxy.java
public ProcessResult loadFromProxy(HttpServletRequest request, HttpServletResponse response, String uri, String servletPath, String proxyPath) throws ServletException, IOException { //System.out.println("LOAD "+uri); //System.out.println("LOAD "+proxyPath); if ("CONNECT".equalsIgnoreCase(request.getMethod())) { handleConnect(request, response); } else {//w w w .j av a2s .c o m URL url = new URL(uri); URLConnection connection = url.openConnection(); connection.setAllowUserInteraction(false); // Set method HttpURLConnection http = null; if (connection instanceof HttpURLConnection) { http = (HttpURLConnection) connection; http.setRequestMethod(request.getMethod()); http.setInstanceFollowRedirects(false); } // check connection header String connectionHdr = request.getHeader("Connection"); if (connectionHdr != null) { connectionHdr = connectionHdr.toLowerCase(); if (connectionHdr.equals("keep-alive") || connectionHdr.equals("close")) connectionHdr = null; } // copy headers boolean xForwardedFor = false; boolean hasContent = false; Enumeration enm = request.getHeaderNames(); while (enm.hasMoreElements()) { // TODO could be better than this! String hdr = (String) enm.nextElement(); String lhdr = hdr.toLowerCase(); if (_DontProxyHeaders.contains(lhdr)) continue; if (connectionHdr != null && connectionHdr.indexOf(lhdr) >= 0) continue; if ("content-type".equals(lhdr)) hasContent = true; Enumeration vals = request.getHeaders(hdr); while (vals.hasMoreElements()) { String val = (String) vals.nextElement(); if (val != null) { connection.addRequestProperty(hdr, val); xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr); } } } // Proxy headers connection.setRequestProperty("Via", "1.1 (jetty)"); if (!xForwardedFor) connection.addRequestProperty("X-Forwarded-For", request.getRemoteAddr()); // a little bit of cache control String cache_control = request.getHeader("Cache-Control"); if (cache_control != null && (cache_control.indexOf("no-cache") >= 0 || cache_control.indexOf("no-store") >= 0)) connection.setUseCaches(false); // customize Connection try { connection.setDoInput(true); // do input thang! InputStream in = request.getInputStream(); if (hasContent) { connection.setDoOutput(true); IOUtils.copy(in, connection.getOutputStream()); } // Connect connection.connect(); } catch (Exception e) { e.printStackTrace(); } InputStream proxy_in = null; // handler status codes etc. int code = 500; if (http != null) { proxy_in = http.getErrorStream(); code = http.getResponseCode(); response.setStatus(code, http.getResponseMessage()); } if (proxy_in == null) { try { proxy_in = connection.getInputStream(); } catch (Exception e) { e.printStackTrace(); proxy_in = http.getErrorStream(); } } // clear response defaults. response.setHeader("Date", null); response.setHeader("Server", null); // set response headers int h = 0; String hdr = connection.getHeaderFieldKey(h); String val = connection.getHeaderField(h); while (hdr != null || val != null) { String lhdr = hdr != null ? hdr.toLowerCase() : null; if (hdr != null && val != null && !_DontProxyHeaders.contains(lhdr)) { if (hdr.equalsIgnoreCase("Location")) { val = Rewriter.translateCleanUrl(val, servletPath, proxyPath); } response.addHeader(hdr, val); } h++; hdr = connection.getHeaderFieldKey(h); val = connection.getHeaderField(h); } boolean isGzipped = connection.getContentEncoding() != null && connection.getContentEncoding().contains("gzip"); response.addHeader("Via", "1.1 (jetty)"); // boolean process = connection.getContentType() == null // || connection.getContentType().isEmpty() // || connection.getContentType().contains("html"); boolean process = connection.getContentType() != null && connection.getContentType().contains("text"); if (proxy_in != null) { if (!process) { IOUtils.copy(proxy_in, response.getOutputStream()); proxy_in.close(); } else { InputStream in; if (isGzipped && proxy_in != null && proxy_in.available() > 0) { in = new GZIPInputStream(proxy_in); } else { in = proxy_in; } ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream(); IOUtils.copy(in, byteArrOS); in.close(); if (in != proxy_in) proxy_in.close(); String charset = response.getCharacterEncoding(); if (charset == null || charset.isEmpty()) { charset = "ISO-8859-1"; } String originalContent = new String(byteArrOS.toByteArray(), charset); byteArrOS.close(); return new ProcessResult(originalContent, connection.getContentType(), charset, isGzipped); } } } return null; }