Reputation: 65
Team,
When i try to read the Request Param attribute values that contains ampersand (&) in spring Boot rest api i am getting Number Format Exception. Below is sample code which i tried. Please Suggest me on this.
Request URL : http://loacalhost:8080/search/ad?skey="uc"&fn="M&M"
Rest Controller method:
@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
) {
.....
}
Exception is : "java.lang.NumberFormatException: For input string: "M&M""
I tried below ways also :
fn="M%26M" , fn=""M%26amp;M" , fn=""M&M" in each case below was the exception i am getting.
"java.lang.NumberFormatException: For input string: "M%26M"", "M%26amp;M"" "M&M""
As suggested i tried below .
@SpringBootTest(classes = Application.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public 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());
}
}
Error is: java.lang.NumberFormatException: For input string: "C%26S"
Upvotes: 3
Views: 1574
Reputation: 187
Try this:
@GetMapping("/example")
public Map<String, String[]> getExample(HttpServletRequest request) {
return request.getParameterMap();
}
And the URI would be:
?skey="uc"&fn="M%26M"
And the response in JSON format
{
"skey": [
"\"uc\""
],
"fn": [
"\"M&M\""
]
}
You also can extract the single parameter if you know it's name by using
request.getParameter("skey");
Upvotes: 1
Reputation: 3671
You have to do URL encoding when sending the request. If you are testing the API manually, then you have to encode it yourself.
eg.
http://loacalhost:8080/search/ad?skey="uc%26fn%3D%22M%26M"
Else if you are using RestTemplate to test this API, then you can use something like this:
eg.
String url = UriComponentsBuilder
.fromUriString("http://loacalhost:8080/search/ad")
.queryParam("skey", "uc&fn=\"M&M").encode().toUriString();
new RestTemplate().getForEntity(url, String.class).getBody();
Upvotes: 0