如何在控制器中使用Spring HttpRequest?

问题描述:

我已经以此方式设置了测试

I've set up my test this way

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

    @Autowired
    private MockMvc mvc;

这是我的控制器签名

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

现在它似乎正在注入代理值,但是例如,如果调用request.getURI(),它似乎为空.

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

我正在尝试执行此操作,以便可以将请求传递给UriComponentsBuilder.fromHttpRequest( ),该请求由控制器中以前的linkTo方法调用,并且它们没有获得代理/空值.

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.

如何获取HttpRequest? (注意:我不希望/不能使用HttpServletRequest,它可以很好地通过,但不是UriComponentsBuilder

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

所以我可以使用HttpServletRequest

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

但是必须包装吗?通过ServletServerHttpRequest获得我想要的界面.

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

HttpRequest httpRequest = new ServletServerHttpRequest( request )