Spring 4.1.1, mockmvc and do not want to encode an HTTP GET request HTTP request

Using MockMVC in tests, and I need to check the GET URL, which is already URL encoded:

http://host:port/app/controller/[ALREADY URL ENCODED] 

The code:

 mockmvc.perform(get("/controller/[ALREADY URL ENCODED]") 

However, in the logs, I see that the URL has been re-encoded by the URL before it goes to the appropriate controller method. Is there any way to prevent spring mockmvc for url encoding? Perhaps disable url encoding in test?

This is an example of the string [[SUSPENDED URL ENCODED] ":

 MEUwQzBBMD8wPTAJBgUrDgMCGgUABBQ%2Fm36Fj2BE19VBYXRO62zrgIYp0gQVAQazEyvlq22wsMBkRyAeaUiZ%2BhTUAgMGJbQ%3D 

This is the URL again before the controller sees it.

This is from logs (the string was re-encoded at the url)

 xxxxx [main] DEBUG [ostwsTestDispatcherServlet] DispatcherServlet with name '' processing GET request for [/app/controller/MEUwQzBBMD8wPTAJBgUrDgMCGgUABBQ%252Fm36Fj2BE19VBYXRO62zrgIYp0gQVAQazEyvlq22wsMBkRyAeaUiZ%252BhTUAgMGJbQ%253D] 

Please note that if I invoke the use of CURL, then there is no url encoding executed by the spring framework, and the controller receives what is sent. However, mockmvc would do the encoding before it gets the appropriate controller method.

 curl -X GET http:host:port/app/controller/[ALREADY URL ENCODED] 

Thanks.

+5
source share
2 answers

What works for me is MockMvcRequestBuilders.get(new URI([ENCODED_URL_STRING])) .

I am assuming there is an alternative using MockMvcRequestBuilders.get(String urlTemplate, Object... urlVariables) , with the corresponding urlVariables, but I do not go deep.

+3
source

A little late, but I created my own URI matches for use with MockMvc:

 public class RequestToUriMatcher implements RequestMatcher { private final String expectedUri; public RequestToUriMatcher(String expectedUri){ this.expectedUri = expectedUri; } @Override public void match(ClientHttpRequest clientHttpRequest) throws IOException, AssertionError { URI requestUri = clientHttpRequest.getURI(); //requestUri is encoded, so if request was made with query parameter already encoded, this would be double-encoded, so decoding it once here String decodedUri = URLDecoder.decode(requestUri.toString(), "UTF-8"); assertTrue(decodedUri.endsWith(expectedUri)); } } 

The following is the static method:

 public static RequestMatcher requestToUri(String uri){ return new RequestToUriMatcher(uri); } 

Now I can use it like this:

 String uri = "stuff%3Dvalue"; MockRestServiceServer.createServer(restTemplate) .expect(requestToUri(uri))/**/ 

This is not an ideal solution, but for the sake of the lack of other solutions, it works ...

+1
source

Source: https://habr.com/ru/post/1206119/


All Articles