Java 如何在Spring Boot Rest API中读取包含符号(&;)的@Request Param属性值
团队 当我试图读取SpringBootRESTAPI中包含符号(&)的请求参数属性值时,我得到了数字格式异常。下面是我尝试过的示例代码。请就此向我提出建议 请求URL:http://loacalhost:8080/search/ad?skey=“uc”&fn=“M&M” Rest控制器方法:Java 如何在Spring Boot Rest API中读取包含符号(&;)的@Request Param属性值,java,spring,spring-boot,spring-mvc,spring-rest,Java,Spring,Spring Boot,Spring Mvc,Spring Rest,团队 当我试图读取SpringBootRESTAPI中包含符号(&)的请求参数属性值时,我得到了数字格式异常。下面是我尝试过的示例代码。请就此向我提出建议 请求URL:http://loacalhost:8080/search/ad?skey=“uc”&fn=“M&M” Rest控制器方法: @GetMapping(value = "/search/ad") public ResponseEntity<List<SearchResultDTO>> fi
@GetMapping(value = "/search/ad")
public ResponseEntity<List<SearchResultDTO>> findSearchResult(
@RequestParam(value="skey",required=true) String skey,
@RequestParam(value="fn",required=false,defaultValue = "null") String fn
) {
.....
}
@GetMapping(value=“/search/ad”)
公共响应发现搜索结果(
@RequestParam(value=“skey”,required=true)字符串skey,
@RequestParam(value=“fn”,required=false,defaultValue=“null”)字符串fn
) {
.....
}
异常为:“java.lang.NumberFormatException:对于输入字符串:“M&M”
我还尝试了以下方法:
fn=“M%26M”,fn=“”M%26amp;M“,fn=”“M&M”在以下每种情况下都是我得到的例外
“java.lang.NumberFormatException:对于输入字符串:“M%26M”“M%26amp;M”“M&M”
正如我建议的,我在下面试过了
@SpringBootTest(class=Application.class,webEnvironment=SpringBootTest.webEnvironment.RANDOM\u端口)
公共类SearchIntegrationTest{
@LocalServerPort
private int port;
@Autowired
TestRestTemplate testRestTemplate;
@Test
public void findearchResult_IntegrationTest() throws JSONException {
String url = UriComponentsBuilder.fromUriString("/search/ad").queryParam("skey", "uc")
.queryParam("pf", "C&S").encode().toUriString();
ResponseEntity<String> response = testRestTemplate.getForEntity(url, String.class);
assertEquals(HttpStatus.OK, response.getStatusCode());
}
@LocalServerPort
专用int端口;
@自动连线
TestRestTemplate TestRestTemplate;
@试验
public void findearchResult_IntegrationTest()抛出JSONException{
字符串url=UriComponentsBuilder.fromUristing(“/search/ad”).queryParam(“skey”、“uc”)
.queryParam(“pf”、“C&S”).encode().toUriString();
ResponseEntity response=testRestTemplate.getForEntity(url,String.class);
assertEquals(HttpStatus.OK,response.getStatusCode());
}
}
错误是:java.lang.NumberFormatException:对于输入字符串:“C%26S”发送请求时必须进行URL编码。如果您是手动测试API,那么您必须自己对其进行编码 例如 否则,如果您正在使用RestTemplate测试此API,则可以使用如下内容: 例如 试试这个:
@GetMapping("/example")
public Map<String, String[]> getExample(HttpServletRequest request) {
return request.getParameterMap();
}
以及JSON格式的响应
{
"skey": [
"\"uc\""
],
"fn": [
"\"M&M\""
]
}
如果知道单个参数的名称,还可以使用
request.getParameter("skey");
不,为了测试目的,我尝试了在swagger UI中进行测试,并尝试了在浏览器url中获取api调用。然后,您必须手动编码这些符号(&)、等于(=)和引号(“)Sry Abhinaba,请求uri中的微小更改,我已经更新了请求url,还尝试了编码方式,但问题仍然存在。
?skey="uc"&fn="M%26M"
{
"skey": [
"\"uc\""
],
"fn": [
"\"M&M\""
]
}
request.getParameter("skey");