programing

Java에서의 HTTP URL 주소 부호화

prostudy 2022. 7. 10. 21:44
반응형

Java에서의 HTTP URL 주소 부호화

Java 스탠드아론 어플리케이션이 사용자로부터 URL(파일을 가리키는 것)을 취득하고, 그것을 눌러 다운로드해야 합니다.현재 직면한 문제는 HTTP URL 주소를 올바르게 인코딩할 수 없다는 것입니다.

예제:

URL:  http://search.barnesandnoble.com/booksearch/first book.pdf

java.net.URLEncoder.encode(url.toString(), "ISO-8859-1");

반환:

http%3A%2F%2Fsearch.barnesandnoble.com%2Fbooksearch%2Ffirst+book.pdf

근데 제가 원하는 건

http://search.barnesandnoble.com/booksearch/first%20book.pdf

(공간이 %20으로 대체됨)

, 아, 아, 맞다.URLEncoderHTTP URL 입니다.JavaDoc의 "HTML"입니다.른른른른 른른른?

java.net 입니다.URI 클래스는 도움이 됩니다.URL 매뉴얼에 있습니다.

URI 클래스는 특정 상황에서 컴포넌트 필드의 이스케이프를 수행합니다.URL 인코딩 및 디코딩을 관리하는 권장 방법은 URI를 사용하는 것입니다.

다음과 같이 둘 이상의 인수가 있는 생성자 중 하나를 사용합니다.

URI uri = new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/first book.pdf",
    null);
URL url = uri.toURL();
//or String request = uri.toString();

(URI의 단일 인수 컨스트럭터는 부정한 문자를 회피하지 않습니다)


코드에 만이 이스케이프 됩니다.비는 이스케이프 되지 .ASC를 이용하다II (fatih) ii ii ii 。
toASCIIString 는, US-ASCII 「US-ASCII」)으로 문자열을 취득할 수.

URI uri = new URI(
    "http", 
    "search.barnesandnoble.com", 
    "/booksearch/é",
    null);
String request = uri.toASCIIString();

"URL"과 같은 http://www.google.com/ig/api?weather=São Paulo5 를

URI uri = new URI(
        "http", 
        "www.google.com", 
        "/ig/api",
        "weather=São Paulo",
        null);
String request = uri.toASCIIString();

상기 답변의 대부분은 올바르지 않습니다.

URLEncoder이름에도 불구하고, 클래스는 여기에 있어야 할 필요가 없습니다.Sun이 이 수업의 이름을 그렇게 짜증나게 지었다는 것은 유감이다. URLEncoder는 데이터를 파라미터로 전달하기 위한 것이지 URL 자체를 인코딩하기 위한 것은 아닙니다.

말하면, 「 」입니다."http://search.barnesandnoble.com/booksearch/first book.pdf" 입니다를 들어 、 음 、 음 、 음음음음음이다."http://search.barnesandnoble.com/booksearch/first book.pdf?parameter1=this&param2=that". 할 수 URLEncoder참조해 주세요.

다음 두 가지 예는 두 가지 간의 차이를 강조합니다.

HTTP 표준에 따라 잘못된 파라미터가 생성됩니다.앰퍼샌드(&)와 플러스(+)가 올바르게 부호화되어 있지 않은 것에 주의해 주세요.

uri = new URI("http", null, "www.google.com", 80, 
"/help/me/book name+me/", "MY CRZY QUERY! +&+ :)", null);

// URI: http://www.google.com:80/help/me/book%20name+me/?MY%20CRZY%20QUERY!%20+&+%20:)

다음으로 쿼리가 올바르게 인코딩된 올바른 파라미터가 생성됩니다.공백, 앰퍼샌드 및 플러스 마크를 적어 둡니다.

uri = new URI("http", null, "www.google.com", 80, "/help/me/book name+me/", URLEncoder.encode("MY CRZY QUERY! +&+ :)", "UTF-8"), null);

// URI: http://www.google.com:80/help/me/book%20name+me/?MY+CRZY+QUERY%2521+%252B%2526%252B+%253A%2529

Android 유저를 대상으로 한 제안을 추가하겠습니다.이렇게 하면 외부 라이브러리를 가져올 필요가 없어집니다.또한 위의 답변 중 일부에서 제시된 문자 검색/바꾸기 솔루션은 모두 위험하므로 피해야 합니다.

시험해 보세요.

String urlStr = "http://abc.dev.domain.com/0007AC/ads/800x480 15sec h.264.mp4";
URL url = new URL(urlStr);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();

이 특정 URL에서 요청에 사용할 수 있도록 이러한 공간을 인코딩해야 합니다.

Android 클래스에서 사용할 수 있는 몇 가지 기능을 활용합니다.첫 번째로 URL 클래스는 URL을 적절한 컴포넌트로 분할할 수 있으므로 문자열 검색/바꾸기 작업을 수행할 필요가 없습니다.둘째, 이 접근법은 단일 문자열이 아닌 컴포넌트를 통해 URI를 구축할 때 컴포넌트를 적절하게 이스케이프하는 URI 클래스 기능을 활용합니다.

이 접근법의 장점은 유효한 URL 스트링을 직접 알 필요 없이 사용할 수 있다는 것입니다.

제가 개발한 솔루션으로 다른 어떤 솔루션보다 훨씬 안정적입니다.

public class URLParamEncoder {

    public static String encode(String input) {
        StringBuilder resultStr = new StringBuilder();
        for (char ch : input.toCharArray()) {
            if (isUnsafe(ch)) {
                resultStr.append('%');
                resultStr.append(toHex(ch / 16));
                resultStr.append(toHex(ch % 16));
            } else {
                resultStr.append(ch);
            }
        }
        return resultStr.toString();
    }

    private static char toHex(int ch) {
        return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
    }

    private static boolean isUnsafe(char ch) {
        if (ch > 128 || ch < 0)
            return true;
        return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
    }

}

URL이 있는 경우 url.toString()을 이 메서드에 전달할 수 있습니다.첫 번째 디코딩은 이중 인코딩을 피하기 위해 (예를 들어 공간을 인코딩하면 %20이 되고 백분율 기호를 인코딩하면 %25가 되므로 이중 인코딩하면 공간이 %2520이 됩니다.)그런 다음 위에서 설명한 대로 URI를 사용하여 URL의 모든 부분을 추가합니다(쿼리 파라미터를 드롭하지 않도록).

public URL convertToURLEscapingIllegalCharacters(String string){
    try {
        String decodedURL = URLDecoder.decode(string, "UTF-8");
        URL url = new URL(decodedURL);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); 
        return uri.toURL(); 
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

Yeah URL 인코딩은 해당 문자열을 인코딩하여 최종 수신처에 URL로 올바르게 전달합니다.예를 들어 http://stackoverflow.com?url=http://yyy.com은 사용할 수 없습니다.Url 매개 변수를 인코딩하면 해당 매개 변수 값이 수정됩니다.

두 가지 선택이 있습니다

  1. 도메인과는 다른 경로에 액세스할 수 있습니까?이 경우 단순히 UrlEncode 경로를 지정할 수 있습니다.단, 그렇지 않은 경우 옵션2가 적합할 수 있습니다.

  2. commons-httpclient-3.1을 가져옵니다.여기에는 URIUtil 클래스가 있습니다.

    System.out.println (URIUtil.encodePath("http://example.com/x y", "ISO-8859-1"));

URI의 패스 부분만 부호화되므로 원하는 대로 출력됩니다.

참고로 이 메서드가 런타임에 작동하려면 commons-codec과 commons-logging이 필요합니다.

프로젝트에 종속성을 추가하지 않으려는 사용자가 있다면 이러한 기능이 도움이 될 수 있습니다.

URL의 '경로' 부분을 여기에 전달합니다.전체 URL을 매개 변수로 전달하고 싶지 않을 수 있습니다(쿼리 문자열에는 다른 이스케이프가 필요함 등).

/**
 * Percent-encodes a string so it's suitable for use in a URL Path (not a query string / form encode, which uses + for spaces, etc)
 */
public static String percentEncode(String encodeMe) {
    if (encodeMe == null) {
        return "";
    }
    String encoded = encodeMe.replace("%", "%25");
    encoded = encoded.replace(" ", "%20");
    encoded = encoded.replace("!", "%21");
    encoded = encoded.replace("#", "%23");
    encoded = encoded.replace("$", "%24");
    encoded = encoded.replace("&", "%26");
    encoded = encoded.replace("'", "%27");
    encoded = encoded.replace("(", "%28");
    encoded = encoded.replace(")", "%29");
    encoded = encoded.replace("*", "%2A");
    encoded = encoded.replace("+", "%2B");
    encoded = encoded.replace(",", "%2C");
    encoded = encoded.replace("/", "%2F");
    encoded = encoded.replace(":", "%3A");
    encoded = encoded.replace(";", "%3B");
    encoded = encoded.replace("=", "%3D");
    encoded = encoded.replace("?", "%3F");
    encoded = encoded.replace("@", "%40");
    encoded = encoded.replace("[", "%5B");
    encoded = encoded.replace("]", "%5D");
    return encoded;
}

/**
 * Percent-decodes a string, such as used in a URL Path (not a query string / form encode, which uses + for spaces, etc)
 */
public static String percentDecode(String encodeMe) {
    if (encodeMe == null) {
        return "";
    }
    String decoded = encodeMe.replace("%21", "!");
    decoded = decoded.replace("%20", " ");
    decoded = decoded.replace("%23", "#");
    decoded = decoded.replace("%24", "$");
    decoded = decoded.replace("%26", "&");
    decoded = decoded.replace("%27", "'");
    decoded = decoded.replace("%28", "(");
    decoded = decoded.replace("%29", ")");
    decoded = decoded.replace("%2A", "*");
    decoded = decoded.replace("%2B", "+");
    decoded = decoded.replace("%2C", ",");
    decoded = decoded.replace("%2F", "/");
    decoded = decoded.replace("%3A", ":");
    decoded = decoded.replace("%3B", ";");
    decoded = decoded.replace("%3D", "=");
    decoded = decoded.replace("%3F", "?");
    decoded = decoded.replace("%40", "@");
    decoded = decoded.replace("%5B", "[");
    decoded = decoded.replace("%5D", "]");
    decoded = decoded.replace("%25", "%");
    return decoded;
}

테스트:

@Test
public void testPercentEncode_Decode() {
    assertEquals("", percentDecode(percentEncode(null)));
    assertEquals("", percentDecode(percentEncode("")));

    assertEquals("!", percentDecode(percentEncode("!")));
    assertEquals("#", percentDecode(percentEncode("#")));
    assertEquals("$", percentDecode(percentEncode("$")));
    assertEquals("@", percentDecode(percentEncode("@")));
    assertEquals("&", percentDecode(percentEncode("&")));
    assertEquals("'", percentDecode(percentEncode("'")));
    assertEquals("(", percentDecode(percentEncode("(")));
    assertEquals(")", percentDecode(percentEncode(")")));
    assertEquals("*", percentDecode(percentEncode("*")));
    assertEquals("+", percentDecode(percentEncode("+")));
    assertEquals(",", percentDecode(percentEncode(",")));
    assertEquals("/", percentDecode(percentEncode("/")));
    assertEquals(":", percentDecode(percentEncode(":")));
    assertEquals(";", percentDecode(percentEncode(";")));

    assertEquals("=", percentDecode(percentEncode("=")));
    assertEquals("?", percentDecode(percentEncode("?")));
    assertEquals("@", percentDecode(percentEncode("@")));
    assertEquals("[", percentDecode(percentEncode("[")));
    assertEquals("]", percentDecode(percentEncode("]")));
    assertEquals(" ", percentDecode(percentEncode(" ")));

    // Get a little complex
    assertEquals("[]]", percentDecode(percentEncode("[]]")));
    assertEquals("a=d%*", percentDecode(percentEncode("a=d%*")));
    assertEquals(")  (", percentDecode(percentEncode(")  (")));
    assertEquals("%21%20%2A%20%27%20%28%20%25%20%29%20%3B%20%3A%20%40%20%26%20%3D%20%2B%20%24%20%2C%20%2F%20%3F%20%23%20%5B%20%5D%20%25",
                    percentEncode("! * ' ( % ) ; : @ & = + $ , / ? # [ ] %"));
    assertEquals("! * ' ( % ) ; : @ & = + $ , / ? # [ ] %", percentDecode(
                    "%21%20%2A%20%27%20%28%20%25%20%29%20%3B%20%3A%20%40%20%26%20%3D%20%2B%20%24%20%2C%20%2F%20%3F%20%23%20%5B%20%5D%20%25"));

    assertEquals("%23456", percentDecode(percentEncode("%23456")));

}

★★★★★★★★★★★★★★★★★★★.org.apache.commons.httpclient.util.URIUtil권장되지 않습니다.replacement org.apache.commons.codec.net.URLCodec 폼 투고에 을 하고 ? 저는 컴포넌트가 있는 하지 않음)를직접 .

public static String encodeURLComponent(final String s)
{
  if (s == null)
  {
    return "";
  }

  final StringBuilder sb = new StringBuilder();

  try
  {
    for (int i = 0; i < s.length(); i++)
    {
      final char c = s.charAt(i);

      if (((c >= 'A') && (c <= 'Z')) || ((c >= 'a') && (c <= 'z')) ||
          ((c >= '0') && (c <= '9')) ||
          (c == '-') ||  (c == '.')  || (c == '_') || (c == '~'))
      {
        sb.append(c);
      }
      else
      {
        final byte[] bytes = ("" + c).getBytes("UTF-8");

        for (byte b : bytes)
        {
          sb.append('%');

          int upper = (((int) b) >> 4) & 0xf;
          sb.append(Integer.toHexString(upper).toUpperCase(Locale.US));

          int lower = ((int) b) & 0xf;
          sb.append(Integer.toHexString(lower).toUpperCase(Locale.US));
        }
      }
    }

    return sb.toString();
  }
  catch (UnsupportedEncodingException uee)
  {
    throw new RuntimeException("UTF-8 unsupported!?", uee);
  }
}

불행히도 발견한 것처럼 URLEncoding은 HTTP URL을 올바르게 인코딩할 수 있습니다.전달한 문자열 "http://search.barnesandnoble.com/booksearch/first book.pdf"는 URL 인코딩 형식으로 올바르게 완전히 인코딩되었습니다.파라미터로 반환된 gobbledigook의 긴 문자열 전체를 URL로 전달하여 전달한 문자열로 다시 디코딩할 수 있습니다.

URL 전체를 파라미터로 전달하는 것과는 조금 다른 작업을 하고 싶은 것 같습니다.제가 아는 바로는 "http://search.barnesandnoble.com/booksearch/whateverTheUserPassesIn"과 같은 검색 URL을 작성하려고 합니다.부호화할 필요가 있는 것은 "무엇이든"User Passes In" 비트는 다음과 같습니다.

String url = "http://search.barnesandnoble.com/booksearch/" + 
       URLEncoder.encode(userInput,"UTF-8");

그것은 당신에게 더 유효한 무언가를 만들어 낼 것입니다.

이전 답변의 솔루션으로는 제대로 동작하지 않아 독자적인 방법을 쓰기 위해 이전 답변을 읽었는데, 이 답변과 일치하지 않는 URL을 찾을 수 있으면 알려주세요.

public static URL convertToURLEscapingIllegalCharacters(String toEscape) throws MalformedURLException, URISyntaxException {
            URL url = new URL(toEscape);
            URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
            //if a % is included in the toEscape string, it will be re-encoded to %25 and we don't want re-encoding, just encoding
            return new URL(uri.toString().replace("%25", "%"));
}

URL에 인코딩된 "/"(%2F)가 있는 경우에도 문제가 있습니다.

RFC 3986 - 섹션 2.2에는 "URI 컴포넌트의 데이터가 딜리미터로서 예약된 문자의 목적과 경합하는 경우 충돌하는 데이터는 URI를 형성하기 전에 퍼센트로 인코딩해야 합니다." (RFC 3986 - 섹션 2.2)

그러나 Tomcat에는 다음과 같은 문제가 있습니다.

http://tomcat.apache.org/security-6.html - Apache Tomcat 6.0.10으로 수정

중요:디렉토리 트래버설 CVE-2007-0450

Tomcat은 '\', '%2F' 및 '%5C' [...]를 허용합니다.

다음 Java 시스템속성이 Tomcat에 추가되어 URL의 패스 딜리미터 처리를 더욱 제어할 수 있게 되었습니다(두 옵션 모두 기본적으로 false).

  • org.disc.disc.buf 입니다.UDecoder.ALLOW_ENCODED_SLASH: true|false
  • org.disc.inna.disc.disc코요테 어댑터ALLOW_BACKSLASH: true|false

모든 URL이 프록시 서버에 있는 것처럼 Tomcat에 의해 처리되는 것을 보증할 수 없기 때문에 컨텍스트액세스를 제한하는 프록시가 사용되지 않은 것처럼 Tomcat은 항상 보안을 유지해야 합니다.

영향: 6.0.0~6.0.9

따라서 %2F 문자가 포함된 URL이 있는 경우 Tomcat은 "400 Invalid URI: noSlash"를 반환합니다.

Tomcat 부팅 스크립트에서 오류 수정을 전환할 수 있습니다.

set JAVA_OPTS=%JAVA_OPTS% %LOGGING_CONFIG%   -Dorg.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH=true 

맷의 말에 동의해요.실제로 튜토리얼에서는 잘 설명한 적이 없지만, 한 가지 문제는 URL 경로를 인코딩하는 방법이며, URL에 부가되는 파라미터(쿼리 부분, "?" 기호 뒤에)를 인코딩하는 방법입니다.이들은 비슷한 인코딩을 사용하지만 동일하지는 않습니다.

특히 공백 문자를 인코딩하는 데 사용됩니다.URL 경로에서는 %20으로 인코딩해야 하지만 쿼리 부분에서는 %20과 "+" 기호를 허용합니다.가장 좋은 방법은 웹 브라우저를 사용하여 웹 서버에 대해 직접 테스트하는 것입니다.

두 경우 모두 문자열 전체가 아니라 항상 구성 요소별로 인코딩합니다.실제로 URLEncoder는 쿼리 부분에 대해 이를 허용합니다.경로 부분에는 클래스 URI를 사용할 수 있지만 이 경우 단일 컴포넌트가 아닌 문자열 전체를 요구합니다.

어쨌든, 이러한 문제를 피하는 가장 좋은 방법은 개인적이고 경합이 없는 디자인을 사용하는 것이라고 생각합니다. 어떻게요?예를 들어 디렉토리나 파라미터에는 a-Z, A-Z, 0-9 및 _ 이외의 문자를 사용하여 이름을 붙이지 않습니다.이렇게 하면 모든 파라미터의 값을 부호화할 수 있습니다.이는 사용자 입력에서 발신되어 사용된 문자를 알 수 없기 때문입니다.

org.springframework.web.util에서 UriUtils를 시도해 볼 수 있습니다.

UriUtils.encodeUri(input, "UTF-8")

이 경우에도 하실 수 있습니다.GUAVA 패스 " " " " 。UrlEscapers.urlFragmentEscaper().escape(relativePath)

위의 내용을 취합하여 조금 변경하였습니다.저는 우선 긍정적인 논리를 좋아하고, HashSet은 String을 통한 검색과 같은 다른 옵션보다 더 나은 성능을 제공할 수 있다고 생각했습니다.오토박싱 패널티가 가치가 있는지는 모르겠지만 컴파일러가 ASCII 문자를 최적화하면 박싱 비용이 낮아집니다.

/***
 * Replaces any character not specifically unreserved to an equivalent 
 * percent sequence.
 * @param s
 * @return
 */
public static String encodeURIcomponent(String s)
{
    StringBuilder o = new StringBuilder();
    for (char ch : s.toCharArray()) {
        if (isSafe(ch)) {
            o.append(ch);
        }
        else {
            o.append('%');
            o.append(toHex(ch / 16));
            o.append(toHex(ch % 16));
        }
    }
    return o.toString();
}

private static char toHex(int ch)
{
    return (char)(ch < 10 ? '0' + ch : 'A' + ch - 10);
}

// https://tools.ietf.org/html/rfc3986#section-2.3
public static final HashSet<Character> UnreservedChars = new HashSet<Character>(Arrays.asList(
        'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
        'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',
        '0','1','2','3','4','5','6','7','8','9',
        '-','_','.','~'));
public static boolean isSafe(char ch)
{
    return UnreservedChars.contains(ch);
}

Carlos Heuberger의 답변과 더불어 기본(80)과 다른 것이 필요한 경우 7개의 파라미터 컨스트럭터를 사용해야 합니다.

URI uri = new URI(
        "http",
        null, // this is for userInfo
        "www.google.com",
        8080, // port number as int
        "/ig/api",
        "weather=São Paulo",
        null);
String request = uri.toASCIIString();

다음 표준 Java 솔루션을 사용합니다(Web Plattform 테스트에서 제공되는 테스트 케이스 중 약 100개를 통과).

0. URL이 이미 인코딩되어 있는지 테스트합니다.

1. URL을 구조적인 부분으로 분할합니다.사용하다java.net.URL할 수 있을 것 같아요.

2. 각 구조 부품을 올바르게 인코딩합니다!

3. 사용IDN.toASCII(putDomainNameHere)Punycode에 호스트 이름을 인코딩합니다.

4. 사용java.net.URI.toASCIIString()percent-encode, NFC 부호화 Unicode - (NFKC!가 좋습니다)

자세한 내용은 이쪽:https://stackoverflow.com/a/49796882/1485527

만약 당신이 봄을 사용하고 있다면, 당신은 시도할 수 있다.org.springframework.web.util.UriUtils#encodePath

HTTP URL을 구성하는 데 도움이 되는 새로운 프로젝트를 만들었습니다.라이브러리는 자동으로 경로 세그먼트와 쿼리 매개 변수를 URL 인코딩합니다.

https://github.com/Widen/urlbuilder 에서 소스를 표시하고 바이너리를 다운로드할 수 있습니다.

이 질문의 URL 예는 다음과 같습니다.

new UrlBuilder("search.barnesandnoble.com", "booksearch/first book.pdf").toString()

생산하다

http://search.barnesandnoble.com/booksearch/first%20book.pdf

저도 같은 문제가 있었어요.언서핑을 통해 해결:

android.net.Uri.encode(urlString, ":/");

문자열은 인코딩되지만 ":" 및 "/"는 건너뜁니다.

저는 이 목적을 위한 도서관을 개발합니다. 갈리마티아스입니다.웹 브라우저와 동일한 방식으로 URL을 구문 분석합니다.즉, 브라우저에서 URL이 작동하면 galimatias에 의해 올바르게 구문 분석됩니다.

이 경우:

// Parse
io.mola.galimatias.URL.parse(
    "http://search.barnesandnoble.com/booksearch/first book.pdf"
).toString()

제공 내용:http://search.barnesandnoble.com/booksearch/first%20book.pdf물론 이것은 가장 간단한 경우이지만, 어떤 경우에도 효과가 있습니다.java.net.URI.

https://github.com/smola/galimatias 에서 확인하실 수 있습니다.

나는 이것을 사용한다.

org.apache.commons.text.StringEscapeUtils.escapeHtml4("my text % & < >");

이 부양가족을 추가하다.

 <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-text</artifactId>
        <version>1.8</version>
    </dependency>

이런 기능을 사용할 수 있습니다.필요에 따라 다음 작업을 완료하고 수정합니다.

/**
     * Encode URL (except :, /, ?, &, =, ... characters)
     * @param url to encode
     * @param encodingCharset url encoding charset
     * @return encoded URL
     * @throws UnsupportedEncodingException
     */
    public static String encodeUrl (String url, String encodingCharset) throws UnsupportedEncodingException{
            return new URLCodec().encode(url, encodingCharset).replace("%3A", ":").replace("%2F", "/").replace("%3F", "?").replace("%3D", "=").replace("%26", "&");
    }

사용 예:

String urlToEncode = ""http://www.growup.com/folder/intérieur-à_vendre?o=4";
Utils.encodeUrl (urlToEncode , "UTF-8")

결과는 http://www.growup.com/folder/int%C3%A9rieur-%C3%A0_vendre?o=4 입니다.

그럼 어떻게 해?

공용 문자열 UrlEncode(String in_) {

String retVal = "";

try {
    retVal = URLEncoder.encode(in_, "UTF8");
} catch (UnsupportedEncodingException ex) {
    Log.get().exception(Log.Level.Error, "urlEncode ", ex);
}

return retVal;

}

언급URL : https://stackoverflow.com/questions/724043/http-url-address-encoding-in-java

반응형