Deprecated Apache Commons HttpClient 3.x:
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
String uriTest1(String uri) {
String encodedUri = null;
try {
encodedUri = URIUtil.encodePath(uri,"UTF-8");
} catch (URIException e) {
System.err.println("Caught URI Exception");
e.printStackTrace();
}
return encodedUri;
}URIEncoder encodes to
application/x-www-form-urlencoded
(i.e. spaces turn to +)import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.net.URLEncoder;
String uriTest2(String uri) {
String encodedUri = null;
String encoding = "UTF-8";
try {
encodedUri = URLEncoder.encode(uri, encoding);
} catch (UnsupportedEncodingException e) {
System.err.println("Unsuported encoding: "+encoding);
e.printStackTrace();
}
return encodedUri;
}
java.net.URI requires the whole URI to be input, but you can extract just the URI encoded query part (turns spaces to %20)
import java.net.URI;
String encodedUri = null;
URI uri = null;
try {
uri = new URI("http","bbc.co.uk","/search/news/",path,null);
} catch (URISyntaxException e) {
System.err.println("Caught URI Syntax Exception");
e.printStackTrace();
}
encodedUri = uri.getRawQuery();
return encodedUri;
}
See also.