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.


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();
    .setParameter("username", "Hello Günter")
    .setParameter("p1", "parameter 1");

Output will be:

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 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. this one replaces only unsafe ASCII characters (like ç, é...).

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


the resulting validURLString will be:


which is a well-formatted URL.

By : dgiugg

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);
By : DnBase

This video can help you solving your question :)
By: admin