Issue
I'm new in spring.
I'm trying to get data from youtube's api using webclient
My service layer look like this
@Service
public class YoutubeService implements YTB {
private WebClient webClient;
private final String API_KEY="";
public YoutubeService() {
webClient=WebClient.create("https://youtube.googleapis.com/youtube/v3/");
}
public YoutubeService(WebClient webClient) {
this.webClient = webClient;
}
public List<youtubeData> getData(String id){
return webClient.get()
.uri("/videos?part=snippet%2Cstatistics&id="+id+"&key="+API_KEY)
.retrieve()
.bodyToFlux(youtubeData.class)
.collectList()
.block();
}
}
And my controller:
@RestController
@RequestMapping("/ytbapi")
public class ytbController {
@Autowired
private YTB service;
@GetMapping("/getData/{id}")
public List<youtubeData> show(@PathVariable String id){
return service.getData(id);
}
}
It work fine when I set
uri("/videos?part=snippet&id="+id+"&key="+API_KEY")
But when I change it to like above and run, I got HTTP Status 500
Request processing failed; nested exception is org.springframework.web.reactive.function.client.WebClientResponseException$BadRequest: 400 Bad Request from GET https://youtube.googleapis.com/youtube/v3/videos?part=snippet%252Cstatistics&id=r9LqfLM93Hw&key=AIzaSyDpPf8w8YN4O6KSiedVUwusiPhU-HP4Iek
The problem is something add 25 in this part: snippet%252Cstatistics
How should I fix it?
Solution
In your URI string "/videos?part=snippet%2Cstatistics&id="+id+"&key="+API_KEY
you have a character "%" which has a so called reserved meaning.
uri(String uri, Object... uriVariables)
method of UriSpec
class uses DefaultUriBuilderFactory
by default under the hood, which uses UriComponentsBuilder
's encode()
method by default. So, symbol "%" is encoded to "%25" in your URI.
You can check what symbols are encoded and to what here.
You used "%2C" in your URI, so I believe you meant "," there.
As URL-encoding is the default behavior of WebClient
, you can define you uri path in unencoded way with a simple coma like this:
.uri("/videos?part=snippet,statistics&id="+id+"&key="+API_KEY)
Answered By - AndrewThomas
Answer Checked By - Katrina (JavaFixing Volunteer)