With external library:
import org.apache.commons.httpclient.util.URIUtil;
String myUrl_1= "http://one.two/three?four five";
System.out.println(URIUtil.encodeQuery(myUrl_1));
And the output:
http://one.two/three?four%20five
Or
String webResourceURL = "http://stackoverflow.com/search?q=<script>alert(1)</script> s";
System.out.println(URIUtil.encodeQuery(webResourceURL));
And the output:
http://stackoverflow.com/search?q=%3Cscript%3Ealert(1)%3C/script%3E%20s
And the Maven dependency
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>