views:

66

answers:

2

I am doing the following:

String url = String.format(WEBSERVICE_WITH_CITYSTATE, cityName, stateName);
String urlUtf8 = new String(url.getBytes(), "UTF8");
Log.d(TAG, "URL: [" + urlUtf8 + "]");
Reader reader = WebService.queryApi(url);

The output that I am looking for is essentially to get the city name with blanks (e.g., "Overland Park") to be formatted as Overland%20Park.

Is it this the best way?

+1  A: 

Assuming you are actually wanting to encode your string for use in a URL (ie, "Overland Park" can also be formatted as "Overland+Park") you want URLEncoder.encode(url, "UTF-8"). Other unsafe characters will be converted to the %xx format you are asking for.

Recurse
Yup! Thanks for the correction. I changed over to the URLEncoder class.
mobibob
Should be double quotes, right?
GregS
Yes, double quotes. Opps.
Recurse
@Recurse: you can edit your own question/answer (or anyone's question/answer when you have 2000 rep) on SO. I replaced the single quote by double quotes in your answer ;)
Webinator
+1  A: 

The simple answer is to use URLEncoder.encode(...) as stated by @Recurse. However, if part or all of the URL has already been encoded, then this can lead to double encoding. For example:

http://foo.com/pages/Hello%20There

or

http://foo.com/query?keyword=what%3f

Another concern with URLEncoder.encode(...) is that it doesn't understand that certain characters should be escaped in some contexts and not others. So for example, a '?' in a query parameter should be escaped, but the '?' that marks the start of the "query part" should not be escaped.

I think that safer way to add missing escapes would be the following:

String safeURI = new URI(url).toASCIIString();

However, I haven't tested this ...

Stephen C
I encountered the problem as you stated. What I chose to do was to only encode the parameter portion and format those results into the URL string. My problem isn't general purpose -- the service is very specific, but I did want to apply best practices and not move data around any more than necessary.
mobibob