如何使用HttpServletRequest捕获Java中的Header请求

时间:2017-05-11 06:40:28

标签: java spring servlets

我想在java中捕获一个标题。我写的代码是正确的。尽管如此,它仍然是空的。你能否请一下这些变化。我在拦截器中做这个任务。我在控制器类或我需要在控制器类上做的任何配置上是否有任何注释?

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.jose4j.jwk.HttpsJwks;
import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.consumer.InvalidJwtException;
import org.jose4j.jwt.consumer.JwtConsumer;
import org.jose4j.jwt.consumer.JwtConsumerBuilder;
import org.jose4j.keys.resolvers.HttpsJwksVerificationKeyResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

@Configuration
@Component
public class TokenValidateInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        String apiKey;
        System.out.println("Header  "+request.getHeader("xx"));  //Null
        System.out.println("request  "+request);  // request  org.apache.catalina.core.ApplicationHttpRequest@4df9ffc7
        System.out.println("request.tostring  "+request.toString()); // request.tostring  org.apache.catalina.core.ApplicationHttpRequest@e0770ef

I am passing the header using POSTMAN

2 个答案:

答案 0 :(得分:2)

' xx'标头可能不在请求中。

替换

System.out.println("Header  "+request.getHeader("xx"));

Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
    System.out.println("Header  " + headerNames.nextElement());
}

查看服务器从客户端收到的所有标头。

答案 1 :(得分:0)

或者甚至更好。可能也很高兴看到价值:

替换:

System.out.println("Header  "+request.getHeader("xx"));

使用:

Enumeration<String> headerNames = request.getHeaderNames();
while (headerNames.hasMoreElements()) {
    String header = headerNames.nextElement();
    System.out.println("Header  " + header);
    System.out.println("Value  " + request.getHeader(header)));
}