'How to change header value of HttpServletRequest in a HandlerInterceptor?

so as follows I have to change (override) the value of one header in request. I have custom Interceptor that implements HandlerInterceptor. I've tried using HttpServletRequestWrapper, I've override getHeader, getHeaders and getHeaderNames method to return new value, but it doesn't seem to work, or I'm using it the wrong way. Does anybody know how to achieve this? I don't really want to use Filter, its only for one specific controller, not every request.

So what I've tried, here is wrapper:

static class RequestHeaderOverwriteWrapper extends HttpServletRequestWrapper {
private final String newHeader;

RequestHeaderOverwriteWrapper(final HttpServletRequest request, final String header) {
    super(request);
    this.newHeader = header;
}

@Override
public String getHeader(final String name) {
    if (newHeader != null && "Header-To-Change".equals(name)) {
        return newHeader;
    }
    return super.getHeader(name);
}

@Override
public Enumeration<String> getHeaders(final String name) {
    if (newHeader != null && "Header-To-Change".equals(name)) {
        return new IteratorEnumeration(Collections.singletonList(newHeader).iterator());
    }
    return super.getHeaders(name);
}

@Override
public Enumeration<String> getHeaderNames() {
    final List<String> headerNames = new ArrayList<>();
    final Enumeration<String> superHeaderNames = super.getHeaderNames();
    while (superHeaderNames.hasMoreElements()) {
        headerNames.add(superHeaderNames.nextElement());
    }
    if (newHeader != null && !headerNames.contains("Header-To-Change")) {
        headerNames.add("Header-To-Change"); //this header needs to be present, its value has to be overridden
    }
    return new IteratorEnumeration(headerNames.iterator());
}

And I'm not sure hot to call it in Interceptor, preHandle method:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
    //here the RequestHeaderOverwriteWrapper has to be used, but what is the correct way to make it work??
    return true;
}


Solution 1:[1]

This question was asked quite a time ago, so in case anyone would have the same issue, I'll post the answer here: you cannot do what I tried with Interceptors, they cannot change the value on existing header, so you have to use Filter and RequestWrapper like one I posted in question.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Lvsia