response.sendRedirect shows unwanted HttpStatus 302 instead of 307

3k Views Asked by At

I have a small test, which should return a HttpStatus with Temporary Redirect with HttpStatus Code 307.
But it always returns a 302.

@RestController
@RequestMapping(value = "/")
public class Controller {

    @ResponseStatus(HttpStatus.TEMPORARY_REDIRECT ) 
    @RequestMapping(value= "test", method = RequestMethod.GET)
    public void resolveUrl(HttpServletResponse response) throws IOException {
        response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
        response.sendRedirect("https://www.google.com");
    }
}

When I look into the documentation of response.sendRedirect() I can read this:

Sends a temporary redirect response to the client using the specified * redirect location URL.

and the documentation of temporary redirect is a 307:

10.3.8 307 Temporary Redirect

The requested resource resides temporarily under a different URI. Since the redirection MAY be altered on occasion, the client SHOULD continue to use the Request-URI for future requests. This response is only cacheable if indicated by a Cache-Control or Expires header field.

(I know, that I don't need the @ResponseStatus(HttpStatus.TEMPORARY_REDIRECT) or the response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT); but I want to show that it will not work with this things too!)

But my test shows that it was a 302 and not a 307

java.lang.AssertionError: Status expected:<307> but was:<302>

Can somebody explain this?

My small test for this:

@RunWith(SpringRunner.class)
@WebMvcTest(Controller.class)
public class ControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void test() throws Exception {
        MockHttpServletRequestBuilder requestBuilder = get("/test");
        mvc.perform(requestBuilder).andExpect(status().isTemporaryRedirect())
                .andExpect(redirectedUrl("https://www.google.com"));
    }

}

Complete code can be found at github

1

There are 1 best solutions below

0
On

Instead of using sendRedirect, set the Location header in the response object like so:

response.setStatus(HttpServletResponse.SC_TEMPORARY_REDIRECT);
response.setHeader("Location","https://we.google.com");