4

I want encode an URL in a way that special characters like " " (space) are substituted in the correct way (%20 in the case of spaces). No one of the solution I found online is working as expected.

I tryed using apache commons:

import org.apache.commons.lang.StringEscapeUtils;

public class MyTest {

    public static void main(String[] args)  {

        String bla="http://www.bla.com/bla.php?par1=bla bla bla";

        System.out.println(StringEscapeUtils.escapeHtml(bla));

    }
}

But it returns:

http://www.bla.com/bla.php?par1=bla bla bla

I tryed with java.net.URL:

import java.net.MalformedURLException;
import java.net.URL;

public class MyTest {


    public static void main(String[] args) throws MalformedURLException {

        String bla="http://www.bla.com/bla.php?par1=bla bla bla";

        URL url = new URL(bla);


        System.out.println(url);

    }

}

But it returns:

http://www.bla.com/bla.php?par1=bla bla bla

I would expect:

http://www.bla.com/bla.php?par1=bla%20bla%20bla

Is there any way to do that?

user1883212
  • 7,539
  • 11
  • 46
  • 82

1 Answers1

4

Try splitting into a URI with the aid of the URL class:

String sUrl = "http://bla.com:8080/test and test/bla.php?query=bla and bla";
URL url = new URL(sUrl);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
String canonical = uri.toString();

System.out.println(canonical);

Output:

http://bla.com:8080/test%20and%20test/bla.php?query=bla%20and%20bla
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
  • This could potentially cause double encoding if anything in sUrl was already percent encoded. Any ways to solve this? – Pat Myron Aug 15 '18 at 21:21