I've got the following class in my Spring Boot application:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.common.net.HttpHeaders;
@Controller
public class TestController {
@RequestMapping("foo")
public ResponseEntity<?> redirectOnGet() {
return ResponseEntity.status(HttpStatus.FOUND).header(HttpHeaders.LOCATION, "http://www.bbc.co.uk").build();
}
}
When I call that via a GET request, I get a 200 OK back containing the HTML source of BBC.co.uk. So it looks like the redirect is being followed.
According to the HTTP spec section 10.3.3:
If the 302 status code is received in response to a request other than GET or HEAD, the user agent MUST NOT automatically redirect the request unless it can be confirmed by the user
Also it's specific for non-GET responses, it doesn't dictate that GET requests should redirect. So although it could be helpful in some cases, here it isn't so I'd like to avoid that redirect.
So does anyone have any idea how I can Spring not to follow a 302 redirect when returning a response to a GET request? What I am returning the response to will follow the 302 itself.
Looking at SimpleClientHttpRequestFactory
, that could be somewhere I can potentially fix the problem. But after overriding the class & exposing it via a @Bean
, my overridden methods aren't being called. I'm guessing it's not being picked up.
There's a project illustrating the issue here: https://github.com/LTheobald/StackOverflow31266409
The test case is probably the most interesting thing to look at. The MockMVC based method does what I expected, the RestTemplate based one doesn't. This is because RestTemplate is set to follow redirects, while TestRestTemplate (which I'm assuming MockMVC uses) doesn't follow redirects. So how can I get my application to act more like TestRestTemplate when the controllers are called?
Note Regarding the possible duplication of: How can I prevent Spring MVC from doing a redirect? . This question doesn't contain enough information to say why it's redirecting. The original poster could have simply been returning "redirect:something" and Spring would have been doing the right thing.