Как правильно закодировать полную строку http URL? - PullRequest
3 голосов
/ 20 июля 2010

Я получил строку URL-адреса от пользователя и хотел бы преобразовать ее в допустимый http-URL:

"http://one.two/three?four пять " должно превратиться в "http://one.two/three?four%20five"

однако URLEncoder не помогает, так как кодирует всю строку (включая допустимое ": //").

help?

Ответы [ 2 ]

6 голосов
/ 20 июля 2010

Используйте класс URL.Например:

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

Третья строка может отличаться - например, построение нового URL из всех его частей.

3 голосов
/ 07 февраля 2017

С внешней библиотекой:

import org.apache.commons.httpclient.util.URIUtil;
String myUrl_1= "http://one.two/three?four five";
System.out.println(URIUtil.encodeQuery(myUrl_1));

И вывод:

http://one.two/three?four%20five

Или

String webResourceURL = "http://stackoverflow.com/search?q=<script>alert(1)</script> s";
System.out.println(URIUtil.encodeQuery(webResourceURL));

И вывод:

http://stackoverflow.com/search?q=%3Cscript%3Ealert(1)%3C/script%3E%20s

И зависимость Maven

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
...