0

I use Spring android RestTemplate to execute GET request to Youtube API like this:

// 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);

From debug, I can see RestTemplate execute wrong url and I got 400 bad request error:

03-16 12:06:47.651: W/RestTemplate(24970): GET request for "https://www.googleapis.com/youtube/v3/channels?key=MY_KEY&part=id%252Csnippet&forUsername=cnn" resulted in 400 (Bad Request); invoking error handler

I have no idea why RestTemplate try to encode parameter url again, from id%2Csnippet to id%252Csnippet
Is there any way to correct it?

1 Answer 1

4

It just so happens that the RestTemplate#getForObject(..) method that expects a String builds a URI from the given String and encodes it before using it. It uses custom Spring classes to do this. (See the source code.)

You can fix this issue by creating a URI object from your String and pass that to the method.

String url = uriBuilder.build().toString(); // this is right url
URI uri = new URI(url);
MyEntity result =  restTemplate.getForObject(uri, MyEntity.class);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.