Encodes illegal characters in the specified URL's path, query string and anchor according to the URL encoding rules observed in real browsers. For example, this method changes "http://first/?a=b c" to "http://first/?a=b%20c" . @param url the URL to encode @pa
(final URL url, final Charset charset)
| 271 | * @return the encoded URL |
| 272 | */ |
| 273 | public static URL encodeUrl(final URL url, final Charset charset) { |
| 274 | if (!isNormalUrlProtocol(url.getProtocol())) { |
| 275 | return url; // javascript:, about:, data: and anything not supported like foo: |
| 276 | } |
| 277 | |
| 278 | try { |
| 279 | String path = url.getPath(); |
| 280 | if (path != null) { |
| 281 | path = encode(path, PATH_ALLOWED_CHARS, UTF_8); |
| 282 | } |
| 283 | String query = url.getQuery(); |
| 284 | if (query != null) { |
| 285 | query = encode(query, QUERY_ALLOWED_CHARS, charset); |
| 286 | } |
| 287 | String anchor = url.getRef(); |
| 288 | if (anchor != null) { |
| 289 | anchor = encode(anchor, ANCHOR_ALLOWED_CHARS, UTF_8); |
| 290 | } |
| 291 | return createNewUrl(url.getProtocol(), url.getUserInfo(), url.getHost(), |
| 292 | url.getPort(), path, anchor, query); |
| 293 | } |
| 294 | catch (final MalformedURLException e) { |
| 295 | // Impossible... I think. |
| 296 | throw new RuntimeException(e); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | /** |
| 301 | * Encodes and escapes the specified URI anchor string. |