我使用 Spring androidRestTemplate
对 Youtube API 执行 GET 请求,如下所示:
// build rest template
RestTemplate restTemplate = new RestTemplate();
GsonHttpMessageConverter jsonConverter = new GsonHttpMessageConverter();
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
StringHttpMessageConverter stringHttpMessageConverter = new StringHttpMessageConverter();
final List<HttpMessageConverter<?>> listHttpMessageConverters = restTemplate.getMessageConverters();
listHttpMessageConverters.add(jsonConverter);
listHttpMessageConverters.add(formHttpMessageConverter);
listHttpMessageConverters.add(stringHttpMessageConverter);
restTemplate.setMessageConverters(listHttpMessageConverters);
Uri.Builder uriBuilder = Uri.parse(https://www.googleapis.com/youtube/v3/channels).buildUpon();
uriBuilder.appendQueryParameter("key", API_KEY);
uriBuilder.appendQueryParameter("part", "id,snippet");
uriBuilder.appendQueryParameter("forUsername", channelName);
String url = uriBuilder.build().toString(); // this is right url
// like this: https://www.googleapis.com/youtube/v3/channels?key=MY_KEY&part=id%2Csnippet&forUsername=cnn
MyEntity result = restTemplate.getForObject(url, MyEntity.class);
从调试中,我可以看到RestTemplate
执行错误的 url,我得到了400 bad request error
:
03-16 12:06:47.651: W/RestTemplate(24970): GET 请求“ https://www.googleapis.com/youtube/v3/channels?key=MY_KEY&part=id%252Csnippet&forUsername=cnn ”导致 400 (错误的请求); 调用错误处理程序
我不知道为什么RestTemplate
要再次尝试对参数 url 进行编码,从id%2Csnippet
toid%252Csnippet
有没有办法纠正它?