Java - Convert String to valid URI object


I am trying to get a 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? b gives whereas I want the output to be

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.

5/27/2015 1:27:13 PM

Accepted Answer

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

Like this (see URIUtil):

URIUtil.encodeQuery(" b")

will become:

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

5/15/2014 9:27:04 PM

Android has always had the Uri class as part of the SDK:

You can simply do something like:

String requestURL = String.format("", Uri.encode("foo bar"), Uri.encode("100% fubar'd"));

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow