Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I encode a complete http url String correctly?

Tags:

java

urlencode

I get a url string from a user and would like to transform it to a legal http url:

"http://one.two/three?four five" should turn into "http://one.two/three?four%20five"

however, URLEncoder does not help, as it encodes the entire string (including the legal "://").

help?

like image 942
Amir Arad Avatar asked Dec 28 '22 09:12

Amir Arad


1 Answers

Use the URL class. For example:

URL url = new URL(urlString);
String encodedQueryString = URLEncoder.encode(url.getQuery());
String encodedUrl = urlString.replace(url.getQuery(), encodedQueryString);

The third line might be different - for example constructing a new URL from all its parts.

like image 141
Bozho Avatar answered Jan 10 '23 11:01

Bozho