74

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=a b 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.

lostInTransit
  • 70,519
  • 61
  • 198
  • 274

11 Answers11

58

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

user2340612
  • 10,053
  • 4
  • 41
  • 66
Hans Doggen
  • 1,796
  • 2
  • 16
  • 13
  • Thanks Hans. I am trying to do this in an Android app. So I have access to a limited number of libraries. Do you have any other suggestions? Thanks again – lostInTransit Feb 21 '09 at 20:53
  • 2
    Perhaps you could have a look at the source of the URIUtil class (it is open source after all). I would assume that it is possible to extract the necessary code from that class. – Hans Doggen Feb 22 '09 at 15:39
  • 7
    The pointed project (Apache commons-httpclient) "is now end of life". It has been in part replaced by [HttpComponents-httpclient](http://hc.apache.org/httpcomponents-client-ga) but I could not manage to find an equivalent method in the new API. – dgiugg Aug 06 '14 at 13:24
  • 2
    I agree with dgiugg. The answer is deprecated. – Sarp Kaya Apr 07 '15 at 03:04
  • 1
    IT seems like it does not exist for new versions of the apache commits -httpclient – Daniel Jun 18 '15 at 21:42
  • http://stackoverflow.com/questions/2605757/what-happened-to-uriutil-encodepath-from-commons-httpclient-3-1 – Daniel Jun 18 '15 at 21:54
45

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"));
bensnider
  • 3,742
  • 1
  • 24
  • 25
  • 4
    Thanks a lot! It's ridiculous how long it takes sometimes to find a simple Java function! – Abdo Sep 27 '12 at 07:57
  • 1
    Unfortunately, the encode() method is crap when trying to encode forward slashes ("/"). I just used a plain old String.replace() to get the job done. That was very lame... searchQuery.replace("/", "%2f"); – Bogdan Zurac Feb 28 '13 at 17:12
34

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.

Craig B
  • 4,763
  • 1
  • 25
  • 19
14

Even if this is an old post with an already accepted answer, I post my alternative answer because it works well for the present issue and it seems nobody mentioned this method.

With the java.net.URI library:

URI uri = URI.create(URLString);

And if you want a URL-formatted string corresponding to it:

String validURLString = uri.toASCIIString();

Unlike many other methods (e.g. java.net.URLEncoder) this one replaces only unsafe ASCII characters (like ç, é...).


In the above example, if URLString is the following String:

"http://www.domain.com/façon+word"

the resulting validURLString will be:

"http://www.domain.com/fa%C3%A7on+word"

which is a well-formatted URL.

dgiugg
  • 1,294
  • 14
  • 23
  • 1
    your answer was the one I was looking for, I couldn't extract the parameter for various reasons and this is the only method that truly worked. – Ramin Dec 14 '15 at 09:14
  • And everybody should also have a look at documentation when dealing with exceptions http://developer.android.com/reference/java/net/URI.html#create(java.lang.String) – Junior Mayhé Dec 28 '15 at 20:22
  • This doesn't seem to convert quotes? i.e. ' " – behelit Nov 01 '17 at 04:38
  • 1
    @behelit True that, just checked. However, [`'` is a safe character](http://www.ietf.org/rfc/rfc1738.txt). But `"` raises an exception! Same thing with java.net.URL. – dgiugg Nov 02 '17 at 08:39
9

If you don't like libraries, how about this?

Note that you should not use this function on the whole URL, instead you should use this on the components...e.g. just the "a b" component, as you build up the URL - otherwise the computer won't know what characters are supposed to have a special meaning and which ones are supposed to have a literal meaning.

/** Converts a string into something you can safely insert into a URL. */
public static String encodeURIcomponent(String s)
{
    StringBuilder o = new StringBuilder();
    for (char ch : s.toCharArray()) {
        if (isUnsafe(ch)) {
            o.append('%');
            o.append(toHex(ch / 16));
            o.append(toHex(ch % 16));
        }
        else o.append(ch);
    }
    return o.toString();
}

private static char toHex(int ch)
{
    return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}

private static boolean isUnsafe(char ch)
{
    if (ch > 128 || ch < 0)
        return true;
    return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
}
Tim Cooper
  • 10,023
  • 5
  • 61
  • 77
  • This does not work (at least in some cases). E.g. character 'Š' is encoded as '%M1', but should be encoded as '%C5%A0'. – mindas May 10 '11 at 10:47
  • This also doesn't work for characters such as tab. I would suggest that this be changed to be unsafe if it doesn't match [A-Za-z0-9_-.~]. See http://en.wikipedia.org/wiki/Percent-encoding – Gray Jul 19 '11 at 20:06
4

You can use the multi-argument constructors of the URI class. From the URI javadoc:

The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.

So if you use

URI uri = new URI("http", "www.google.com?q=a b");

Then you get http:www.google.com?q=a%20b which isn't quite right, but it's a little closer.

If you know that your string will not have URL fragments (e.g. http://example.com/page#anchor), then you can use the following code to get what you want:

String s = "http://www.google.com?q=a b";
String[] parts = s.split(":",2);
URI uri = new URI(parts[0], parts[1], null);

To be safe, you should scan the string for # characters, but this should get you started.

Community
  • 1
  • 1
Jason Day
  • 8,809
  • 1
  • 41
  • 46
4

I had similar problems for one of my projects to create a URI object from a string. I couldn't find any clean solution either. Here's what I came up with :

public static URI encodeURL(String url) throws MalformedURLException, URISyntaxException  
{
    URI uriFormatted = null; 

    URL urlLink = new URL(url);
    uriFormatted = new URI("http", urlLink.getHost(), urlLink.getPath(), urlLink.getQuery(), urlLink.getRef());

    return uriFormatted;
}

You can use the following URI constructor instead to specify a port if needed:

URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);
Giacomo1968
  • 25,759
  • 11
  • 71
  • 103
Hervé Donner
  • 523
  • 1
  • 6
  • 13
  • Doesn't handle converting a question mark (I tried it with the URL: `http://www.google.com/Do you like Spam?` and it took care of the spaces, but not the question mark at the end) – kentcdodds Mar 27 '12 at 18:57
  • @kentcdodds it's because the question mark is legal in this case. I'm sure that if you add another one after, it would be converted – Sebas Jan 12 '16 at 16:55
3

Well I tried using

String converted = URLDecoder.decode("toconvert","UTF-8");

I hope this is what you were actually looking for?

Amol Ghotankar
  • 2,008
  • 5
  • 28
  • 42
  • This is the answer that I was looking for and requires no dependency on outside libraries. – Michael Plautz Aug 01 '14 at 17:12
  • 1
    No this is wrong answer. `URLDecoder.decode("to convert","UTF-8") `returns "to convert" and `URLDecoder.decode("to%20convert","UTF-8")` returns "to convert". So this does the opposite of what the question is asking. – Sarp Kaya Apr 07 '15 at 03:25
1

Or perhaps you could use this class:

http://developer.android.com/reference/java/net/URLEncoder.html

Which is present in Android since API level 1.

Annoyingly however, it treats spaces specially (replacing them with + instead of %20). To get round this we simply use this fragment:

URLEncoder.encode(value, "UTF-8").replace("+", "%20");

MrCranky
  • 1,498
  • 24
  • 32
  • 1
    This would give http://www.google.com?q=a+b not http://www.google.com?q=a%20b as desired. – cutts Mar 07 '11 at 14:42
  • Ah, yes, found that myself a few weeks afterwards. Will modify answer to reflect what we actually end up using – MrCranky Mar 08 '11 at 09:39
  • 1
    This method is now depreciated, users should specify a method on encoding see: http://docs.oracle.com/javase/1.4.2/docs/api/java/net/URLEncoder.html – Aidanc Nov 12 '13 at 18:49
  • True, I missed that. Answer amended. – MrCranky Nov 14 '13 at 10:06
1

The java.net blog had a class the other day that might have done what you want (but it is down right now so I cannot check).

This code here could probably be modified to do what you want:

http://svn.apache.org/repos/asf/incubator/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/uri/UriBuilder.java

Here is the one I was thinking of from java.net: https://urlencodedquerystring.dev.java.net/

TofuBeer
  • 60,850
  • 18
  • 118
  • 163
0

I ended up using the httpclient-4.3.6:

import org.apache.http.client.utils.URIBuilder;
public static void main (String [] args) {
    URIBuilder uri = new URIBuilder();
    uri.setScheme("http")
    .setHost("www.example.com")
    .setPath("/somepage.php")
    .setParameter("username", "Hello Günter")
    .setParameter("p1", "parameter 1");
    System.out.println(uri.toString());
}

Output will be:

http://www.example.com/somepage.php?username=Hello+G%C3%BCnter&p1=paramter+1