List of usage examples for javax.servlet.http HttpServletRequest getHeaders
public Enumeration<String> getHeaders(String name);
Enumeration
of String
objects. From source file:org.opengeoportal.proxy.controllers.OldDynamicOgcController.java
/** Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = (String) enumerationOfHeaderNames.nextElement(); //TODO why? // if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) // continue; if (hopByHopHeaders.containsHeader(headerName)) 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 headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) { String headerValue = (String) headers.nextElement(); //Don't do this unless we need to /*if (headerName.equalsIgnoreCase(HttpHeaders.USER_AGENT)){ headerValue = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0"; }*//*from w ww.j av a2 s . c o m*/ // 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 = URIUtils.extractHost(this.targetUri); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); } proxyRequest.addHeader(headerName, headerValue); } } }
From source file:it.geosdi.era.server.servlet.HTTPProxy.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request/*w ww . j a v a 2 s . co 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 */ @SuppressWarnings("unchecked") private void setProxyRequestHeaders(URL url, HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) { this.stringProxyHost = url.getHost(); this.intProxyPort = url.getPort(); this.stringProxyPath = url.getPath(); // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) 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 enumerationOfHeaderValues = 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(); } // Skip GZIP Responses if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_ACCEPT_ENCODING) && stringHeaderValue.toLowerCase().contains("gzip")) continue; if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_CONTENT_ENCODING) && stringHeaderValue.toLowerCase().contains("gzip")) continue; if (stringHeaderName.equalsIgnoreCase(HTTP_HEADER_TRANSFER_ENCODING)) continue; Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:it.greenvulcano.gvesb.adapter.http.mapping.ForwardHttpServletMapping.java
@SuppressWarnings("deprecation") @Override/* w w w .j a va 2 s. c om*/ public void handleRequest(String methodName, HttpServletRequest req, HttpServletResponse resp) throws InboundHttpResponseException { logger.debug("BEGIN forward: " + req.getRequestURI()); final HttpURLConnection httpConnection = (HttpURLConnection) connection; ; try { httpConnection.setRequestMethod(methodName); httpConnection.setReadTimeout(soTimeout); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); if (dump) { StringBuffer sb = new StringBuffer(); DumpUtils.dump(req, sb); logger.info(sb.toString()); } String mapping = req.getPathInfo(); if (mapping == null) { mapping = "/"; } String destPath = contextPath + mapping; String queryString = req.getQueryString(); if (queryString != null) { destPath += "?" + queryString; } if (!destPath.startsWith("/")) { destPath = "/" + destPath; } logger.info("Resulting QueryString: " + destPath); Collections.list(req.getHeaderNames()).forEach(headerName -> { httpConnection.setRequestProperty(headerName, Collections.list(req.getHeaders(headerName)).stream().collect(Collectors.joining(";"))); }); if (methodName.equalsIgnoreCase("POST") || methodName.equalsIgnoreCase("PUT")) { httpConnection.setDoOutput(true); IOUtils.copy(req.getInputStream(), httpConnection.getOutputStream()); } httpConnection.connect(); int status = httpConnection.getResponseCode(); resp.setStatus(status, httpConnection.getResponseMessage()); httpConnection.getHeaderFields().entrySet().stream().forEach(header -> { resp.addHeader(header.getKey(), header.getValue().stream().collect(Collectors.joining(";"))); }); ByteArrayOutputStream bodyOut = new ByteArrayOutputStream(); IOUtils.copy(httpConnection.getInputStream(), bodyOut); OutputStream out = resp.getOutputStream(); out.write(bodyOut.toByteArray()); //IOUtils.copy(method.getResponseBodyAsStream(), out); out.flush(); out.close(); if (dump) { StringBuffer sb = new StringBuffer(); DumpUtils.dump(resp, bodyOut, sb); logger.info(sb.toString()); } } catch (Exception exc) { logger.error("ERROR on forwarding: " + req.getRequestURI(), exc); throw new InboundHttpResponseException("GV_CALL_SERVICE_ERROR", new String[][] { { "message", exc.getMessage() } }, exc); } finally { try { if (httpConnection != null) { httpConnection.disconnect(); } } catch (Exception exc) { logger.warn("Error while releasing connection", exc); } logger.debug("END forward: " + req.getRequestURI()); } }
From source file:com.qlkh.client.server.proxy.ProxyServlet.java
/** * Retrieves all of the headers from the servlet request and sets them on * the proxy request//from w w w . ja v a 2s.com * * @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) { // Get an Enumeration of all of the header names sent by the client Enumeration enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) { 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 enumerationOfHeaderValues = 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(); } Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:org.openanzo.binarystore.server.BinaryStoreServlet.java
@SuppressWarnings("unchecked") private int serveStaticResource(HttpServletRequest request, HttpServletResponse response, String filename, String contentType) throws AnzoException, ServletException { // Find the resource and content HttpContent content = null;/*from w ww.j a va2 s . c o m*/ org.eclipse.jetty.util.resource.Resource resource = null; try { resource = org.eclipse.jetty.util.resource.Resource.newResource("file://" + filename); Enumeration reqRanges = null; // Is this a range request? reqRanges = request.getHeaders(HttpHeaders.RANGE); if (reqRanges != null && !reqRanges.hasMoreElements()) reqRanges = null; // Handle resource if (resource == null || !resource.exists()) return HttpServletResponse.SC_NOT_FOUND; if (!resource.isDirectory()) { // ensure we have content content = new UnCachedContent(resource, contentType); if (passConditionalHeaders(request, response, resource, content)) { sendData(request, response, false, resource, content, reqRanges); } } else { return HttpServletResponse.SC_NOT_FOUND; } } catch (IllegalArgumentException e) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_SENDING_DATA_FAILED, e, filename); } catch (IOException e) { throw new AnzoException(ExceptionConstants.BINARYSTORE.BINARYSTORE_SENDING_DATA_FAILED, e, filename); } finally { if (content != null) { content.release(); } if (resource != null) { resource.release(); } } return HttpServletResponse.SC_OK; }
From source file:com.kurento.kmf.repository.internal.http.RepositoryHttpServlet.java
private void logRequest(HttpServletRequest req) { log.info("Request received " + req.getRequestURL()); log.info(" Method: " + req.getMethod()); Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> values = req.getHeaders(headerName); List<String> valueList = new ArrayList<>(); while (values.hasMoreElements()) { valueList.add(values.nextElement()); }//from www. ja v a 2 s .c o m log.info(" Header {}: {}", headerName, valueList); } }
From source file:org.kurento.repository.internal.http.RepositoryHttpServlet.java
private void logRequest(HttpServletRequest req) { log.debug("Request received " + req.getRequestURL()); log.debug(" Method: " + req.getMethod()); Enumeration<String> headerNames = req.getHeaderNames(); while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); Enumeration<String> values = req.getHeaders(headerName); List<String> valueList = new ArrayList<>(); while (values.hasMoreElements()) { valueList.add(values.nextElement()); }/*from www . j a v a2 s . co m*/ log.debug(" Header {}: {}", headerName, valueList); } }
From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java
/** * The service method from HttpServlet, performs handling of all * HTTP-requests independent of their method. Requests and responses within * the method can be distinguished by belonging to the "frontend" (i.e. the * client connecting to the proxy) or the "backend" (the server being * contacted on behalf of the client)/*ww w . j a va 2 s . c om*/ * * @param frontendRequest Request coming in from the client * @param frontendResponse Response being returned to the client * @throws ServletException * @throws IOException */ @Override protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse) throws ServletException, IOException { log(LogService.LOG_INFO, "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort() + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " " + frontendRequest.getRequestURI()); if (targetBaseUri == null) { // FIXME return status page return; } //////////////////// Setup backend request final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return frontendRequest.getMethod(); } }; try { backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } //////////////////// Copy headers to backend request final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames(); while (frontendHeaderNames.hasMoreElements()) { final String headerName = frontendHeaderNames.nextElement(); final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); if (!headerName.equalsIgnoreCase("Content-Length")) { backendRequest.setHeader(headerName, headerValue); } } } //////////////////// Copy Entity - if any final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream()); if (inEntityBytes.length > 0) { backendRequest.setEntity(new ByteArrayEntity(inEntityBytes)); } //////////////////// Execute request to backend try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) { frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode()); // Copy back headers final Header[] backendHeaders = backendResponse.getAllHeaders(); final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length); for (Header header : backendHeaders) { if (backendHeaderNames.add(header.getName())) { frontendResponse.setHeader(header.getName(), header.getValue()); } else { frontendResponse.addHeader(header.getName(), header.getValue()); } } final ServletOutputStream outStream = frontendResponse.getOutputStream(); // Copy back entity final HttpEntity entity = backendResponse.getEntity(); if (entity != null) { try (InputStream inStream = entity.getContent()) { IOUtils.copy(inStream, outStream); } } outStream.flush(); } }
From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java
/** * Retreives all of the headers from the servlet request and sets them on * the proxy request//from ww w .j av a 2 s .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) { // Get an Enumeration of all of the header names sent by the client Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String stringHeaderName = (String) enumerationOfHeaderNames.nextElement(); if (stringHeaderName.equalsIgnoreCase(HttpConstants.STRING_CONTENT_LENGTH_HEADER_NAME)) continue; // Support gzip transfer encoding if (stringHeaderName.equalsIgnoreCase(HttpConstants.STRING_ACCEPT_ENCODING_HEADER_NAME)) { httpMethodProxyRequest.setRequestHeader(stringHeaderName, "gzip"); 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 = 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(HttpConstants.STRING_HOST_HEADER_NAME)){ // stringHeaderValue = getProxyHostAndPort(); //} Header header = new Header(stringHeaderName, stringHeaderValue); // Set the same header on the proxy request httpMethodProxyRequest.setRequestHeader(header); } } }
From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java
@Override protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException { // debug informations log.debug("doGet"); log.debug("context path: " + request.getContextPath()); log.debug("character encoding: " + request.getCharacterEncoding()); log.debug("content length: " + request.getContentLength()); log.debug("content type: " + request.getContentType()); log.debug("local addr: " + request.getLocalAddr()); log.debug("local name: " + request.getLocalName()); log.debug("local port: " + request.getLocalPort()); log.debug("method: " + request.getMethod()); log.debug("path info: " + request.getPathInfo()); log.debug("path translated: " + request.getPathTranslated()); log.debug("protocol: " + request.getProtocol()); log.debug("query string: " + request.getQueryString()); log.debug("requested session id: " + request.getRequestedSessionId()); log.debug("Host header: " + request.getServerName()); log.debug("servlet path: " + request.getServletPath()); log.debug("request URI: " + request.getRequestURI()); @SuppressWarnings("unchecked") final Enumeration<String> header_names = request.getHeaderNames(); while (header_names.hasMoreElements()) { final String header_name = header_names.nextElement(); log.debug("header name: " + header_name); @SuppressWarnings("unchecked") final Enumeration<String> header_values = request.getHeaders(header_name); while (header_values.hasMoreElements()) log.debug(" " + header_name + " => " + header_values.nextElement()); }//from w ww. j a va 2 s .com if (request.getCookies() != null) for (Cookie cookie : request.getCookies()) { log.debug("cookie:"); log.debug("cookie comment: " + cookie.getComment()); log.debug("cookie domain: " + cookie.getDomain()); log.debug("cookie max age: " + cookie.getMaxAge()); log.debug("cookie name: " + cookie.getName()); log.debug("cookie path: " + cookie.getPath()); log.debug("cookie value: " + cookie.getValue()); log.debug("cookie version: " + cookie.getVersion()); log.debug("cookie secure: " + cookie.getSecure()); } @SuppressWarnings("unchecked") final Enumeration<String> parameter_names = request.getParameterNames(); while (parameter_names.hasMoreElements()) { final String parameter_name = parameter_names.nextElement(); log.debug("parameter name: " + parameter_name); final String[] parameter_values = request.getParameterValues(parameter_name); for (final String parameter_value : parameter_values) log.debug(" " + parameter_name + " => " + parameter_value); } // parse request String target_scheme = null; String target_host; int target_port; // request.getPathInfo() is url decoded final String[] path_info_parts = request.getPathInfo().split("/"); if (path_info_parts.length >= 2) target_scheme = path_info_parts[1]; if (path_info_parts.length >= 3) { target_host = path_info_parts[2]; try { if (path_info_parts.length >= 4) target_port = new Integer(path_info_parts[3]); else target_port = 80; } catch (final NumberFormatException ex) { log.warn(ex); target_port = 80; } } else { target_scheme = "http"; target_host = "www.google.com"; target_port = 80; } log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port); // create forwarding request final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port); final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection(); // be transparent for accept-language headers @SuppressWarnings("unchecked") final Enumeration<String> accepted_languages = request.getHeaders("accept-language"); while (accepted_languages.hasMoreElements()) target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement()); // be transparent for accepted headers @SuppressWarnings("unchecked") final Enumeration<String> accepted_content = request.getHeaders("accept"); while (accepted_content.hasMoreElements()) target_connection.setRequestProperty("Accept", accepted_content.nextElement()); }