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

标签 java spring spring-mvc uri builder

我正在尝试找到一个使用 X-Forwarded-* header 构建新链接的解决方案。

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 ”。我怎样才能摆脱 context-path、setvlet-path 和 request uri?

最佳答案

@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"));

}

有帮助。

关于java - 如何使用 X-Forwarded-* header 创建没有上下文路径的 URI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55745051/

相关文章:

JAVA 如何读取 SQL 并添加到对象数组中

java - 如何在文件上传时为文件名添加时间戳

java - 将 key 添加到选定的 key 集中

java - 使用 Spring 自定义数据源通过 JRDataSource 创建报告模板

Java - Hibernate.cfg.xml - 无法解析文件中的驱动程序

java - 将 Spring boot/cloud 与 Amazon AWS lambda 一起使用不会注入(inject)值

java - Spring WS 在模式实例的命名空间声明方面存在问题

java - 是否可以在 Spring Boot 应用程序中使用具有冗余功能的 HashiCorp Vault?

java - 对于没有 "id"属性的 bean,Spring bean 创建失败

java - Spring MVC - 将相同的对象从一个页面传输到另一个页面