Development Tip

Java-문자열을 유효한 URI 객체로 변환

yourdevel 2020. 10. 28. 21:13
반응형

Java-문자열을 유효한 URI 객체로 변환


에서 java.net.URI개체 를 가져 오려고 합니다 String. 문자열에는 백분율 이스케이프 시퀀스로 대체해야하는 문자가 있습니다. 그러나 URLEncoder를 사용하여 문자열을 UTF-8 인코딩으로 인코딩하면 /조차도 이스케이프 시퀀스로 대체됩니다.

String 객체에서 유효한 인코딩 된 URL을 얻으려면 어떻게해야합니까?

http://www.google.com?q=a b http % 3A % 2F % 2www.google.com ...을 제공 하지만 출력은 http://www.google.com?q=a%가 되기를 원합니다 . 20b

누군가 이것을 달성하는 방법을 알려주십시오.

Android 앱에서이 작업을 수행하려고합니다. 따라서 제한된 수의 라이브러리에 액세스 할 수 있습니다.


당신은 시도 할 수 있습니다 org.apache.commons.httpclient.util.URIUtil.encodeQuery에서 아파치 평민 - HttpClient를의 프로젝트

다음과 같이 ( URIUtil 참조 ) :

URIUtil.encodeQuery("http://www.google.com?q=a b")

될 것입니다:

http://www.google.com?q=a%20b

물론 직접 할 수는 있지만 URI 구문 분석은 매우 지저분해질 수 있습니다.


Android에는 항상 SDK의 일부로 Uri 클래스가 있습니다. http://developer.android.com/reference/android/net/Uri.html

다음과 같이 간단히 할 수 있습니다.

String requestURL = String.format("http://www.example.com/?a=%s&b=%s", Uri.encode("foo bar"), Uri.encode("100% fubar'd"));

여기에 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 문자열을 사용하여 특별한 지식 없이도 작동 할 수 있다는 것입니다.


이것이 이미 받아 들여진 답변이있는 오래된 게시물이더라도 현재 문제에 잘 작동하고 아무도이 방법을 언급하지 않았기 때문에 대체 답변을 게시합니다.

java.net.URI 라이브러리 사용 :

URI uri = URI.create(URLString);

그리고 이에 상응하는 URL 형식의 문자열을 원한다면 :

String validURLString = uri.toASCIIString();

다른 많은 메소드 (예 : java.net.URLEncoder)와 달리이 메소드는 안전하지 않은 ASCII 문자 (예 : ç, é...) 만 대체합니다 .


위의 예 URLString에서 다음과 같은 경우 String:

"http://www.domain.com/façon+word"

결과 validURLString는 다음과 같습니다.

"http://www.domain.com/fa%C3%A7on+word"

올바른 형식의 URL입니다.


도서관이 마음에 들지 않으시면 어떠세요?

전체 URL에서이 기능을 사용해서는 안됩니다. 대신 구성 요소에이 기능을 사용해야합니다. 예를 들어 URL을 작성할 때 "ab"구성 요소 만 사용해야합니다. 특별한 의미를 가지며 어떤 것이 문자적인 의미를 가져야하는지.

/** Converts a string into something you can safely insert into a URL. */
public static String encodeURIcomponent(String s)
{
    StringBuilder o = new StringBuilder();
    for (char ch : s.toCharArray()) {
        if (isUnsafe(ch)) {
            o.append('%');
            o.append(toHex(ch / 16));
            o.append(toHex(ch % 16));
        }
        else o.append(ch);
    }
    return o.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;
}

URI클래스 의 다중 인수 생성자를 사용할 수 있습니다 . 로부터 URI의 javadoc :

The multi-argument constructors quote illegal characters as required by the components in which they appear. The percent character ('%') is always quoted by these constructors. Any other characters are preserved.

So if you use

URI uri = new URI("http", "www.google.com?q=a b");

Then you get http:www.google.com?q=a%20b which isn't quite right, but it's a little closer.

If you know that your string will not have URL fragments (e.g. http://example.com/page#anchor), then you can use the following code to get what you want:

String s = "http://www.google.com?q=a b";
String[] parts = s.split(":",2);
URI uri = new URI(parts[0], parts[1], null);

To be safe, you should scan the string for # characters, but this should get you started.


I had similar problems for one of my projects to create a URI object from a string. I couldn't find any clean solution either. Here's what I came up with :

public static URI encodeURL(String url) throws MalformedURLException, URISyntaxException  
{
    URI uriFormatted = null; 

    URL urlLink = new URL(url);
    uriFormatted = new URI("http", urlLink.getHost(), urlLink.getPath(), urlLink.getQuery(), urlLink.getRef());

    return uriFormatted;
}

You can use the following URI constructor instead to specify a port if needed:

URI uri = new URI(scheme, userInfo, host, port, path, query, fragment);

Well I tried using

String converted = URLDecoder.decode("toconvert","UTF-8");

I hope this is what you were actually looking for?


The java.net blog had a class the other day that might have done what you want (but it is down right now so I cannot check).

This code here could probably be modified to do what you want:

http://svn.apache.org/repos/asf/incubator/shindig/trunk/java/common/src/main/java/org/apache/shindig/common/uri/UriBuilder.java

Here is the one I was thinking of from java.net: https://urlencodedquerystring.dev.java.net/


Or perhaps you could use this class:

http://developer.android.com/reference/java/net/URLEncoder.html

Which is present in Android since API level 1.

Annoyingly however, it treats spaces specially (replacing them with + instead of %20). To get round this we simply use this fragment:

URLEncoder.encode(value, "UTF-8").replace("+", "%20");


I ended up using the httpclient-4.3.6:

import org.apache.http.client.utils.URIBuilder;
public static void main (String [] args) {
    URIBuilder uri = new URIBuilder();
    uri.setScheme("http")
    .setHost("www.example.com")
    .setPath("/somepage.php")
    .setParameter("username", "Hello Günter")
    .setParameter("p1", "parameter 1");
    System.out.println(uri.toString());
}

Output will be:

http://www.example.com/somepage.php?username=Hello+G%C3%BCnter&p1=paramter+1

참고URL : https://stackoverflow.com/questions/573184/java-convert-string-to-valid-uri-object

반응형