Java - How To Encode Url Path For Non Latin Characters
Solution 1:
You should just encode the special characters and the parse them together. If you tried to encode the entire URI then you'd run into problems.
Stick with:
Stringquery= URLEncoder.encode("apples oranges", "utf-8");
Stringurl="http://stackoverflow.com/search?q=" + query;
Check out this great guide on URL encoding.
That being said, a little bit of searching suggests that there may be other ways to do what you want:
Give this a try:
StringurlStr="http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URLurl=newURL(urlStr);
URIuri=newURI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
(You will need to have those spaces encoded so you can use it for a request.)
This takes advantage of a couple features available to you in Android classes. First, the URL class can break a url into its proper components so there is no need for you to do any string search/replace work. Secondly, this approach takes advantage of the URI class feature of properly escaping components when you construct a URI via components rather than from a single string.
The beauty of this approach is that you can take any valid url string and have it work without needing any special knowledge of it yourself.
Solution 2:
finalURLurl=newURL( newURI(urlString).toASCIIString() );
worked for me.
Solution 3:
I did it as below, which is cumbersome
//was: final URL url = new URL(urlString);String asciiString;
try {
asciiString = new URL(urlString).toURI().toASCIIString();
} catch (URISyntaxException e1) {
Log.e(TAG, "Error new URL(urlString).toURI().toASCIIString() " + urlString + " : " + e1);
returnnull;
}
Log.v(TAG, urlString+" -> "+ asciiString );
final URL url = new URL(asciiString);
url
is later used in
connection = (HttpURLConnection) url.openConnection();
Post a Comment for "Java - How To Encode Url Path For Non Latin Characters"