[英]spring 4.1.1, mockmvc and do not want url encoding of HTTP GET request
在測試中使用MockMVC,我需要測試已經URL編碼的GET URL:
http://host:port/app/controller/[ALREADY URL ENCODED]
編碼:
mockmvc.perform(get("/controller/[ALREADY URL ENCODED]")
但是在日志中我看到URL在到達適當的控制器方法之前已經被再次進行了url編碼。 有沒有辦法可以阻止spring mockmvc進行url編碼? 也許在測試中禁用url編碼?
“[ALREADY URL ENCODED]”字符串的真實示例:
MEUwQzBBMD8wPTAJBgUrDgMCGgUABBQ%2Fm36Fj2BE19VBYXRO62zrgIYp0gQVAQazEyvlq22wsMBkRyAeaUiZ%2BhTUAgMGJbQ%3D
這會在控制器看到之前再次對URL進行編碼。
這是來自日志(該字符串已被重新編碼)
xxxxx [main] DEBUG [o.s.t.w.s.TestDispatcherServlet] DispatcherServlet with name '' processing GET request for [/app/controller/MEUwQzBBMD8wPTAJBgUrDgMCGgUABBQ%252Fm36Fj2BE19VBYXRO62zrgIYp0gQVAQazEyvlq22wsMBkRyAeaUiZ%252BhTUAgMGJbQ%253D]
請注意,如果我使用CURL調用,則spring框架不會執行url編碼,並且控制器會獲取發送的內容。 但是,mockmvc會在進入適當的控制器方法之前進行編碼。
curl -X GET http:host:port/app/controller/[ALREADY URL ENCODED]
謝謝。
對我MockMvcRequestBuilders.get(new URI([ENCODED_URL_STRING]))
是MockMvcRequestBuilders.get(new URI([ENCODED_URL_STRING]))
。
我猜有其他方法可以使用MockMvcRequestBuilders.get(String urlTemplate, Object... urlVariables)
和適當的urlVariables,但我沒有更深入。
有點晚了,但我創建了自己的URI匹配器與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));
}
}
其次是靜態方法:
public static RequestMatcher requestToUri(String uri){
return new RequestToUriMatcher(uri);
}
現在我可以像這樣使用它:
String uri = "stuff%3Dvalue";
MockRestServiceServer.createServer(restTemplate)
.expect(requestToUri(uri))/**/
它不是一個完美的解決方案,但為了缺乏其他解決方案,它的工作原理......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.