List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames
public Enumeration<String> getHeaderNames();
From source file:org.ocpsoft.rewrite.servlet.config.proxy.ProxyServlet.java
/** Copy request headers from the servlet client to the proxy request. */ protected void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest) { /*//from w w w. j a v a 2 s . c o m * Get an Enumeration of all of the header names sent by the client */ Enumeration<String> enumerationOfHeaderNames = servletRequest.getHeaderNames(); while (enumerationOfHeaderNames.hasMoreElements()) { String headerName = enumerationOfHeaderNames.nextElement(); // Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) continue; if (hopByHopHeaders.containsHeader(headerName)) continue; 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 = URIUtils.extractHost(this.targetUriObj); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); } proxyRequest.addHeader(headerName, headerValue); } } }
From source file:kornell.server.ProxyServlet.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(); //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) continue; if (hopByHopHeaders.containsHeader(headerName)) continue; Enumeration headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) 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 = URIUtils.extractHost(this.targetUriObj); headerValue = host.getHostName(); if (host.getPort() != -1) headerValue += ":" + host.getPort(); }/*from w w w .jav a 2 s . c o m*/ proxyRequest.addHeader(headerName, headerValue); } } }
From source file:cn.knet.showcase.demos.servletproxy.ProxyServlet.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(); //Instead the content-length is effectively set via InputStreamEntity if (headerName.equalsIgnoreCase(HttpHeaders.CONTENT_LENGTH)) continue; if (hopByHopHeaders.containsHeader(headerName)) continue; Enumeration headers = servletRequest.getHeaders(headerName); while (headers.hasMoreElements()) {//sometimes more than one value String headerValue = (String) 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(); } else if (headerName.equalsIgnoreCase(org.apache.http.cookie.SM.COOKIE)) { headerValue = getRealCookie(headerValue); }//from w w w. jav a 2 s. co m proxyRequest.addHeader(headerName, headerValue); } } }
From source file:com.imaginary.home.cloud.api.RestApi.java
private @Nonnull Map<String, Object> parseHeaders(@Nonnull HttpServletRequest req) throws RestException { @SuppressWarnings("unchecked") Enumeration<String> names = (Enumeration<String>) req.getHeaderNames(); HashMap<String, Object> headers = new HashMap<String, Object>(); while (names.hasMoreElements()) { String name = names.nextElement(); //noinspection unchecked headers.put(name, getHeader(name, req.getHeaders(name))); }//w ww . ja v a 2 s. co m return headers; }
From source file:be.fedict.eid.applet.service.AbstractAppletServiceServlet.java
@SuppressWarnings("unchecked") @Override//from w w w . j a v a2 s . c om protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doPost"); /* * First retrieve the HTTP headers. The unmarshaller may digest the * body, which makes it impossible to retrieve the headers afterwards. */ Map<String, String> httpHeaders = new HashMap<String, String>(); Enumeration<String> headerNamesEnum = request.getHeaderNames(); while (headerNamesEnum.hasMoreElements()) { String headerName = headerNamesEnum.nextElement(); httpHeaders.put(headerName, request.getHeader(headerName)); } /* * Incoming message unmarshaller. */ HttpServletRequestHttpReceiver httpReceiver = new HttpServletRequestHttpReceiver(request, this.skipSecureConnectionCheck); Object transferObject; try { transferObject = this.unmarshaller.receive(httpReceiver); } catch (Exception e) { LOG.debug("unmarshaller error: " + e.getMessage(), e); throw new RuntimeException("unmarshaller error: " + e.getMessage(), e); } /* * Protocol state checker for incoming message. */ HttpServletProtocolContext protocolContext = new HttpServletProtocolContext(request); ProtocolStateMachine protocolStateMachine = new ProtocolStateMachine(protocolContext); CleanSessionProtocolStateListener cleanSessionProtocolStateListener = new CleanSessionProtocolStateListener( request); protocolStateMachine.addProtocolStateListener(cleanSessionProtocolStateListener); RequestContext requestContext = new RequestContext(request); protocolStateMachine.addProtocolStateListener(requestContext); protocolStateMachine.checkRequestMessage(transferObject); /* * Message dispatcher */ Class<?> messageClass = transferObject.getClass(); MessageHandler messageHandler = getMessageHandler(messageClass); if (null == messageHandler) { throw new ServletException("unsupported message"); } HttpSession session = request.getSession(); Object responseMessage = messageHandler.handleMessage(transferObject, httpHeaders, request, session); /* * Check outgoing messages for protocol constraints. */ ResponsesAllowed responsesAllowedAnnotation = messageClass.getAnnotation(ResponsesAllowed.class); if (null != responsesAllowedAnnotation) { /* * Make sure the message handlers respect the protocol. */ if (null == responseMessage) { throw new ServletException("null response message while @ResponsesAllowed constraint was set"); } Class<?>[] responsesAllowed = responsesAllowedAnnotation.value(); if (false == isOfClass(responseMessage, responsesAllowed)) { throw new ServletException("response message type incorrect"); } } /* * Protocol state checker for outgoing message. */ protocolStateMachine.checkResponseMessage(responseMessage); /* * Marshall outgoing message. */ if (null != responseMessage) { HttpServletResponseHttpTransmitter httpTransmitter = new HttpServletResponseHttpTransmitter(response); Transport.transfer(responseMessage, httpTransmitter); } }
From source file:de.goldbachinteractive.gbi.redirecthandler.client.Error404HandlerServlet.java
/** * Requests a redirect processor for redirect (with the original request as * parameter r)./*from w w w .ja v a2 s. co m*/ * * @param redirectProcessorUrl * The redirect processor to use (with the original request as * parameter r). * @param httpClient * The HttpClient to execute the request. * @param req * The original request. * @param resp * The original response. * @param timeout * The timeout for request. * @return True, if redirected or false, if not. */ private boolean redirectRequest(String redirectProcessorUrl, CloseableHttpClient httpClient, HttpServletRequest req, HttpServletResponse resp, int timeout) { try { HttpGet httpGet = new HttpGet(redirectProcessorUrl); httpGet.setConfig(RequestConfig.custom().setRedirectsEnabled(false).setSocketTimeout(timeout).build()); // copy all headers from original request final Enumeration<String> headers = req.getHeaderNames(); while (headers.hasMoreElements()) { final String header = headers.nextElement(); if (header.equalsIgnoreCase("host")) { continue; } final Enumeration<String> values = req.getHeaders(header); while (values.hasMoreElements()) { final String value = values.nextElement(); httpGet.setHeader(header, value); } } // to remove host header if (httpGet.getHeaders("host") != null) { httpGet.removeHeaders("host"); } // to add X-gbi-key header httpGet.setHeader(GBI_KEY_HEADER, xGbiKey); CloseableHttpResponse response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); logger.info(String.format("status code :%d", statusCode)); if (statusCode >= 300 && statusCode < 400) { // if status code is 3XX, the Location header of response is set String location = response.getHeaders("Location")[0].getValue(); resp.sendRedirect(location); return true; } } catch (Exception e) { logger.error(String.format("error while trying to request redirect:[%s]", e.getMessage()), e); } return false; }
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 a v a2 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 */ @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:com.streamsets.pipeline.stage.origin.httpserver.PushHttpReceiver.java
protected Map<String, String> getCustomHeaderAttributes(HttpServletRequest req) { Map<String, String> customHeaderAttributes = new HashMap<>(); customHeaderAttributes.put(PATH_HEADER, StringUtils.stripToEmpty(req.getServletPath())); customHeaderAttributes.put(QUERY_STRING_HEADER, StringUtils.stripToEmpty(req.getQueryString())); customHeaderAttributes.put(METHOD_HEADER, StringUtils.stripToEmpty(req.getMethod())); customHeaderAttributes.put(REMOTE_HOST, StringUtils.stripToEmpty(req.getRemoteHost())); Enumeration<String> headerNames = req.getHeaderNames(); if (headerNames != null) { while (headerNames.hasMoreElements()) { String headerName = headerNames.nextElement(); customHeaderAttributes.put(headerName, req.getHeader(headerName)); }/* w w w.j av a2 s . co m*/ } return customHeaderAttributes; }
From source file:com.shenit.commons.utils.HttpUtils.java
/** * Dump out things from HttpServletRequest object * // w ww.java 2 s. co m * @param req * @return */ public static String dumpRequest(HttpServletRequest req) { if (req == null) return null; char column = ':', rtn = '\n', space = ' '; StringBuilder builder = new StringBuilder(req.getMethod()); builder.append(space).append(req.getRequestURL().toString()).append(space).append(req.getProtocol()) .append(rtn); Enumeration<String> headers = req.getHeaderNames(); builder.append("HEADERS:\n"); String header; for (; headers.hasMoreElements();) { header = headers.nextElement(); builder.append(header).append(column).append(req.getHeader(header)).append(rtn); } builder.append("COOKIES:\n"); Cookie cookie; Cookie[] cookies = req.getCookies(); if (!ValidationUtils.isEmpty(cookies)) { for (int i = 0; i < cookies.length; i++) { cookie = cookies[i]; builder.append(cookie.getName()).append(column).append(GsonUtils.format(cookie)).append(rtn); } } builder.append("BODY:\n"); Map<String, String[]> params = req.getParameterMap(); for (String name : params.keySet()) { builder.append(name).append(ShenStrings.DELIMITER_DOT); builder.append(name.matches(PASS_PATTERN) ? params.get(SECRET_STRING) : params.get(name)); } return builder.toString(); }
From source file:cn.guoyukun.spring.web.filter.DebugRequestAndResponseFilter.java
private void debugRequest(HttpServletRequest request) { log.debug("=====================request begin=========================="); String uri = request.getRequestURI(); String queryString = request.getQueryString(); if (StringUtils.isNotBlank(queryString)) { uri = uri + "?" + queryString; }/* w w w .j av a 2 s . c o m*/ log.debug("{}:{}", request.getMethod(), uri); log.debug("remote ip:{} sessionId:{} ", IpUtils.getIpAddr(request), request.getRequestedSessionId()); log.debug("===header begin============================================"); Enumeration<String> headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); String value = headersToString(request.getHeaders(name)); log.debug("{}={}", name, value); } log.debug("===header end============================================"); log.debug("===parameter begin=========================================="); Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = parameterNames.nextElement(); String value = StringUtils.join(request.getParameterValues(name), "||"); log.debug("{}={}", name, value); } log.debug("===parameter end=========================================="); log.debug("=====================request end=========================="); }