繁体   English   中英

如何在 Spring 引导 Rest API 中读取包含与号 (&) 的 @Request Param 属性值

[英]How to read the @Request Param attribute values that contains ampersand (&) in Spring Boot Rest API

团队,

当我尝试在 spring 引导 rest api 中读取包含与号 (&) 的请求参数属性值时,我收到数字格式异常。 下面是我尝试过的示例代码。 请就此向我提出建议。

请求 URL: http://loacalhost:8080/search/ad?skey="uc"&fn="M&M"

Rest Controller方法:

@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
            ) {
.....
}

例外是:“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(类 = Application.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)公共 class 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());

}

}

错误是:java.lang.NumberFormatException:对于输入字符串:“C%26S”

尝试这个:

@GetMapping("/example")
public Map<String, String[]> getExample(HttpServletRequest request) {
    return request.getParameterMap();
}

URI 将是:

?skey="uc"&fn="M%26M"

以及 JSON 格式的响应

{
    "skey": [
        "\"uc\""
    ],
    "fn": [
        "\"M&M\""
    ]
}

如果您知道单个参数的名称,也可以使用

request.getParameter("skey");

发送请求时必须进行 URL 编码。 如果您要手动测试 API,那么您必须自己对其进行编码。

例如。

http://loacalhost:8080/search/ad?skey="uc%26fn%3D%22M%26M"

否则,如果您使用 RestTemplate 来测试这个 API,那么您可以使用这样的东西:

例如。

String url = UriComponentsBuilder
        .fromUriString("http://loacalhost:8080/search/ad")
        .queryParam("skey", "uc&fn=\"M&M").encode().toUriString();
new RestTemplate().getForEntity(url, String.class).getBody();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM