Android: How to Parse Url String with Spaces to Uri Object

Android: how to parse URL String with spaces to URI object?

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

Java - Convert String to valid URI object

You might try: org.apache.commons.httpclient.util.URIUtil.encodeQuery in Apache commons-httpclient project

Like this (see URIUtil):

URIUtil.encodeQuery("http://www.google.com?q=a b")

will become:

http://www.google.com?q=a%20b

You can of course do it yourself, but URI parsing can get pretty messy...

Turning a string into a Uri in Android

Uri myUri = Uri.parse("http://www.google.com");

Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29

how to insert %20 in place of space in android

Try this:

String temp = http://www.arteonline.mobi/iphone/output.php?gallery=MALBA%20-%20MUSEO%20DE%20ARTE%20LATINOAMERICANO%20DE%20BUENOS%20AIRES

temp = temp.replaceAll(" ", "%20");
URL sourceUrl = new URL(temp);


Related Topics



Leave a reply



Submit