How can I use a Spring HttpRequest in my controlle

2019-07-19 02:14发布

问题:

I've set up my test this way

@SpringBootTest
@AutoConfigureMockMvc
@RunWith( SpringRunner.class )
public class PublicControllerTest {

    @Autowired
    private MockMvc mvc;

this is my controller signature

@GetMapping( produces = MediaTypes.HAL_JSON_VALUE )
ResponseEntity<ResourceSupport> index( final HttpRequest request ) {

now it seems to be injecting a proxy value, but if you call request.getURI() for example, it seems to be null.

I'm trying to do this so I can pass request to UriComponentsBuilder.fromHttpRequest( ), which is called by previous linkTo methods in my controller and they aren't getting a proxy/null.

How can I get HttpRequest? (note: I don't want/can't use HttpServletRequest which gets passed fine but is not the right interface for UriComponentsBuilder

回答1:

So I can use the HttpServletRequest

@GetMapping( produces = MediaTypes.HAL_JSON_VALUE )
ResponseEntity<ResourceSupport> index( final HttpServletRequest request ) {

but it has to be wrapped? by ServletServerHttpRequest to get the interface I want.

HttpRequest httpRequest = new ServletServerHttpRequest( request )