如何使用X-Forwarded- *标头创建没有上下文路径的URI?

时间:2019-04-18 11:27:44

标签: java spring spring-mvc uri builder

我正在尝试找到一种解决方案,该解决方案将使用X-Forwarded- *标头构建新链接。

public class ApiUriBuilderTest {

    private MockHttpServletRequest request = new MockHttpServletRequest();
    private HttpRequest httpRequest = new ServletServerHttpRequest(request);


    @Before
    public void setUp() throws Exception {
        request.setScheme("http");
        request.setServerName("localhost");
        request.setServerPort(80);
        request.setRequestURI("/mvc-showcase");
        request.addHeader("X-Forwarded-Proto", "https");
        request.addHeader("X-Forwarded-Host", "84.198.58.199");
        request.addHeader("X-Forwarded-Port", "443");

        request.setContextPath("/mvc-showcase");
        request.setServletPath("/app");
        request.setRequestURI("/mvc-showcase/app/uri/of/request?hello=world&raw#my-frag");

        httpRequest = new ServletServerHttpRequest(request);

    }

    @Test
    public void test() {
        String uri = ForwardedContextPathServletUriComponentsBuilder.fromRequest(request).build().toUriString();
        assertThat(uri, is("https://84.198.58.199:443"));

    }

    @Test
    public void test_uri_components_builder() throws URISyntaxException {
        UriComponents result = UriComponentsBuilder.fromHttpRequest(httpRequest).build();
        assertEquals("https://84.198.58.199:443", result.toString());
    }

但是返回值为“ https://84.198.58.199/mvc-showcase/app/uri/of/request?hello=world&raw#my-frag”。如何摆脱上下文路径,setvlet路径并请求uri?

1 个答案:

答案 0 :(得分:0)

@Test
public void test() {
    String uri = ServletUriComponentsBuilder.fromRequest(request).replacePath("relativePath").replaceQuery(null).build().toUriString();
    assertThat(uri, is("https://84.198.58.199:8080/relativePath"));

}

有帮助。