Convert String to valid URI object

I am trying to get a java.net.URI object from a String . The string has some characters which will need to be replaced by their percentage escape sequences. But when I use URLEncoder to encode the String with UTF-8 encoding, even the / are replaced with their escape sequences.

How can I get a valid encoded URL from a String object?

http://www.google.com?q=ab gives http%3A%2F%2www.google.com... whereas I want the output to be http://www.google.com?q=a%20b

Can someone please tell me how to achieve this.

I am trying to do this in an Android app. So I have access to a limited number of libraries.


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...


Android has always had the Uri class as part of the SDK: http://developer.android.com/reference/android/net/Uri.html

You can simply do something like:

String requestURL = String.format("http://www.example.com/?a=%s&b=%s", Uri.encode("foo bar"), Uri.encode("100% fubar'd"));

I'm going to add one suggestion here aimed at Android users. You can do this which avoids having to get any external libraries. Also, all the search/replace characters solutions suggested in some of the answers above are perilous and should be avoided.

Give this a try:

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

You can see that in this particular URL, I need to have those spaces encoded so that I 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.

链接地址: http://www.djcxy.com/p/26512.html

上一篇: 如何在C#中为URL创建查询字符串?

下一篇: 将String转换为有效的URI对象