Example usage for javax.servlet.http HttpServletRequest getHeaderNames

List of usage examples for javax.servlet.http HttpServletRequest getHeaderNames

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getHeaderNames.

Prototype

public Enumeration<String> getHeaderNames();

Source Link

Document

Returns an enumeration of all the header names this request contains.

Usage

From source file:org.jkcsoft.web.struts.http.controllers.HttpHelper.java

/**
 *
 */
public static Enumeration getRequestHeaders(HttpServletRequest req) {
    return req.getHeaderNames();
}

From source file:de.micromata.genome.logging.LogRequestDumpAttribute.java

/**
 * Gen http request dump.//w  w w  .ja  va 2  s  . c om
 *
 * @param req the req
 * @return the string
 */
@SuppressWarnings("unchecked")
public static String genHttpRequestDump(HttpServletRequest req) {
    StringBuilder sb = new StringBuilder();

    sb.append("method: ").append(req.getMethod()).append('\n')//
            .append("requestURL: ").append(req.getRequestURL()).append('\n')//
            .append("servletPath: ").append(req.getServletPath()).append('\n')//
            .append("requestURI: ").append(req.getRequestURI()).append('\n') //
            .append("queryString: ").append(req.getQueryString()).append('\n') //
            .append("pathInfo: ").append(req.getPathInfo()).append('\n')//
            .append("contextPath: ").append(req.getContextPath()).append('\n') //
            .append("characterEncoding: ").append(req.getCharacterEncoding()).append('\n') //
            .append("localName: ").append(req.getLocalName()).append('\n') //
            .append("contentLength: ").append(req.getContentLength()).append('\n') //
    ;
    sb.append("Header:\n");
    for (Enumeration<String> en = req.getHeaderNames(); en.hasMoreElements();) {
        String hn = en.nextElement();
        sb.append("  ").append(hn).append(": ").append(req.getHeader(hn)).append("\n");
    }
    sb.append("Attr: \n");
    Enumeration en = req.getAttributeNames();
    for (; en.hasMoreElements();) {
        String k = (String) en.nextElement();
        Object v = req.getAttribute(k);
        sb.append("  ").append(k).append(": ").append(Objects.toString(v, StringUtils.EMPTY)).append('\n');
    }

    return sb.toString();
}

From source file:de.adorsys.oauth.authdispatcher.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param sr              The servlet request. Must not be
 *                        {@code null}.//from   w  w  w.  j  av  a2  s  .c om
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest sr, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(sr.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(sr);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(sr.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = sr.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, sr.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(sr.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && sr.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = sr.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = sr.getReader();

            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}

From source file:jp.pigumer.app.Application.java

@RequestMapping("/")
public String index(HttpServletRequest request, Model model) {
    List<String> headers = new ArrayList<>();
    Enumeration<String> enumHeaders = request.getHeaderNames();
    while (enumHeaders.hasMoreElements()) {
        String name = enumHeaders.nextElement();
        String value = request.getHeader(name);
        headers.add(String.format("%s: %s", name, value));
    }//from www  .  j ava2 s. com
    model.addAttribute("headers", headers);
    return "index";
}

From source file:com.lynn.controller.HttpAction.java

@RequestMapping("/header1.do")
@ResponseBody//from   w ww .ja v  a 2 s  .co  m
public String header1(HttpServletRequest request, HttpServletResponse response) {
    Enumeration e = request.getHeaderNames();
    String query = request.getQueryString();//??get??
    String etag = request.getHeader("etag");
    String if_none_match = request.getHeader("If-None-Match");
    String host = request.getHeader("host");
    String accept = request.getHeader("accept");
    String referer = request.getHeader("referer");
    String host1 = response.getHeader("host");
    String etag1 = response.getHeader("etag");
    String date1 = response.getHeader("date");
    String server1 = response.getHeader("server");
    return query;
}

From source file:net.sf.j2ep.requesthandlers.MaxForwardRequestHandler.java

/**
 * Will write all the headers included in the request to the method.
 * The difference between this method and setHeaders in BasicRequestHandler
 * is that the BasicRequestHandler will also add Via, x-forwarded-for, etc.
 * These "special" headers should not be added when the proxy is target
 * directly with a Max-Forwards: 0 headers.
 * @param method The method to write to/* w ww. j  av  a  2  s .co  m*/
 * @param request The incoming request
 * @see RequestHandlerBase#setHeaders(HttpMethod, HttpServletRequest)
 */
@SuppressWarnings("rawtypes")
private void setAllHeaders(HttpMethod method, HttpServletRequest request) {
    Enumeration headers = request.getHeaderNames();

    while (headers.hasMoreElements()) {
        String name = (String) headers.nextElement();
        Enumeration value = request.getHeaders(name);

        while (value.hasMoreElements()) {
            method.addRequestHeader(name, (String) value.nextElement());
        }

    }
}

From source file:se.inera.certificate.proxy.module.RequestInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    for (String s : Collections.list(request.getHeaderNames())) {
        log.debug(s + ":" + request.getHeader(s));
    }/*  w ww .  j a va 2  s.  c o m*/
    return true;
}

From source file:org.davidmendoza.esu.web.ErrorController.java

@RequestMapping(method = RequestMethod.GET)
public String show(HttpServletRequest request) {
    StringBuilder sb = new StringBuilder();
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String key = (String) headerNames.nextElement();
        sb.append(key).append(":").append(request.getHeader(key)).append("\n");
    }/*from   w w w.  java  2  s .  com*/
    log.error("Error: {}", sb.toString());
    return "error/500";
}

From source file:de.adorsys.oauth.server.FixedServletUtils.java

/**
 * Creates a new HTTP request from the specified HTTP servlet request.
 *
 * @param servletRequest              The servlet request. Must not be
 *                        {@code null}.//from w w w  . j  av a  2  s  .  co m
 * @param maxEntityLength The maximum entity length to accept, -1 for
 *                        no limit.
 *
 * @return The HTTP request.
 *
 * @throws IllegalArgumentException The the servlet request method is
 *                                  not GET, POST, PUT or DELETE or the
 *                                  content type header value couldn't
 *                                  be parsed.
 * @throws IOException              For a POST or PUT body that
 *                                  couldn't be read due to an I/O
 *                                  exception.
 */
public static HTTPRequest createHTTPRequest(final HttpServletRequest servletRequest, final long maxEntityLength)
        throws IOException {

    HTTPRequest.Method method = HTTPRequest.Method.valueOf(servletRequest.getMethod().toUpperCase());

    String urlString = reconstructRequestURLString(servletRequest);

    URL url;

    try {
        url = new URL(urlString);

    } catch (MalformedURLException e) {

        throw new IllegalArgumentException("Invalid request URL: " + e.getMessage() + ": " + urlString, e);
    }

    HTTPRequest request = new HTTPRequest(method, url);

    try {
        request.setContentType(servletRequest.getContentType());

    } catch (ParseException e) {

        throw new IllegalArgumentException("Invalid Content-Type header value: " + e.getMessage(), e);
    }

    Enumeration<String> headerNames = servletRequest.getHeaderNames();

    while (headerNames.hasMoreElements()) {
        final String headerName = headerNames.nextElement();
        request.setHeader(headerName, servletRequest.getHeader(headerName));
    }

    if (method.equals(HTTPRequest.Method.GET) || method.equals(HTTPRequest.Method.DELETE)) {

        request.setQuery(servletRequest.getQueryString());

    } else if (method.equals(HTTPRequest.Method.POST) || method.equals(HTTPRequest.Method.PUT)) {

        if (maxEntityLength > 0 && servletRequest.getContentLength() > maxEntityLength) {
            throw new IOException("Request entity body is too large, limit is " + maxEntityLength + " chars");
        }

        Map<String, String[]> parameterMap = servletRequest.getParameterMap();
        StringBuilder builder = new StringBuilder();

        if (!parameterMap.isEmpty()) {
            for (Entry<String, String[]> entry : parameterMap.entrySet()) {
                String key = entry.getKey();
                String[] value = entry.getValue();
                if (value.length > 0 && value[0] != null) {
                    String encoded = URLEncoder.encode(value[0], "UTF-8");
                    builder = builder.append(key).append('=').append(encoded).append('&');
                }
            }
            String queryString = StringUtils.substringBeforeLast(builder.toString(), "&");
            request.setQuery(queryString);

        } else {
            // read body
            StringBuilder body = new StringBuilder(256);

            BufferedReader reader = servletRequest.getReader();
            reader.reset();
            char[] cbuf = new char[256];

            int readChars;

            while ((readChars = reader.read(cbuf)) != -1) {

                body.append(cbuf, 0, readChars);

                if (maxEntityLength > 0 && body.length() > maxEntityLength) {
                    throw new IOException(
                            "Request entity body is too large, limit is " + maxEntityLength + " chars");
                }
            }

            reader.reset();
            // reader.close();

            request.setQuery(body.toString());
        }
    }

    return request;
}

From source file:cn.sel.wetty.interceptor.AccessLogger.java

private String getHeaders(HttpServletRequest request) {
    Enumeration<String> headerNames = request.getHeaderNames();
    List<String> result = new ArrayList<>();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        result.add(String.format("%s=%s", name, getEnumerationString(request.getHeaders(name))));
    }//  ww w . j a v a 2  s  .c  o m
    return Arrays.toString(result.toArray());
}