Search code examples
javaspringspring-mvcuribuilder

How to create URI without context-path using X-Forwarded-* headers?


I am trying to find a solution which will build a new link using X-Forwarded-* headers.

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());
    }

But the returning value is "https://84.198.58.199/mvc-showcase/app/uri/of/request?hello=world&raw#my-frag". How can I possible get rid of context-path, setvlet-path and request uri?


Solution

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

    helped.