How To Create A Android.net.uri From A Java.net.url?
Solution 1:
Use URL.toURI()
(Android doc) method.
Example:
URLurl=newURL("http://www.google.com"); //Some instantiated URL objectURIuri= url.toURI();
Make sure to handle relevant exception, such as URISyntaxException
.
Solution 2:
I think your answer can be found from here..
Uri.Builder.build()
works quite well with normal URLs, but it fails with port number support.
The easiest way that I discovered to make it support port numbers was to make it parse a given URL first then work with it.
Uri.Builderb= Uri.parse("http://www.yoursite.com:12345").buildUpon();
b.path("/path/to/something/");
b.appendQueryParameter("arg1", String.valueOf(42));
if (username != "") {
b.appendQueryParameter("username", username);
}
Stringurl= b.build().toString();
Source : http://twigstechtips.blogspot.com/2011/01/android-create-url-using.html
Solution 3:
From How to create a Uri from a URL?
Uriuri= Uri.parse( "http://www.facebook.com" );
Solution 4:
Note that in Android, Uri's are different from Java URI's. Here's how to avoid using hardcoded strings, and at the same time, create a Uri with just the path portion of the http URL string encoded to conform to RFC2396:
Sample Url String:
StringthisUrl="http://lapi.transitchicago.com/api/1.0/ttarrivals.aspx?key=[redacted]&mapid=value"
method:
privateUri.Builder builder;
publicUrigetUriFromUrl(String thisUrl) {
URL url = newURL(thisUrl);
builder = newUri.Builder()
.scheme(url.getProtocol())
.authority(url.getAuthority())
.appendPath(url.getPath());
return builder.build();
}
To handle query strings you will need to parse the url.getQuery() as described here and then feed that into builder. appendQueryParameter().
Solution 5:
URI uri = null;
URL url = null;
// Create a URItry {
uri = new URI("www.abc.com");
} catch (URISyntaxException e) {
}
// Convert an absolute URI to a URLtry {
url = uri.toURL();
} catch (IllegalArgumentException e) {
// URI was not absolute
} catch (MalformedURLException e) {
}
// Convert a URL to a URItry {
uri = new URI(url.toString());
} catch (URISyntaxException e) {
}
Post a Comment for "How To Create A Android.net.uri From A Java.net.url?"