Android url转码填坑-中文转码以及特殊字符

先来说几个概念:

URI :Uniform Resource Identifier,统一资源标识符;

URL:Uniform Resource Locator,统一资源定位符;

URN:Uniform Resource Name,统一资源名称。

其中,URL,URN是URI的子集。

Web上地址的基本形式是URI,它代表统一资源标识符。有两种形式:

URL:目前URI的最普遍形式就是无处不在的URL或统一资源定位器。

URN:URL的一种更新形式,统一资源名称(URN, Uniform Resource Name)不依赖于位置,并且有可能减少失效连接的个数。但是其流行还需假以时日,因为它需要更精密软件的支持。

URI是以某种统一的(标准化的)方式标识资源的简单字符串。

通常情况下,我们都会使用utf-8的url转码方式。

但是当你碰到一个比你还不靠谱的后端时,他告诉的信息是这样的:

我们._-$,;~()/这些字符不转义。。。


public static String encode(String s) {
    return encode(s, null);
}

/**
 * Encodes characters in the given string as '%'-escaped octets
 * using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers
 * ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes
 * all other characters with the exception of those specified in the
 * allow argument.

你有没有一种风中凌乱的感觉。。。。

这个时候URI.encode已经救不了你了。

还好还有这个。。。


public static String encode(String s, String allow) {
    if (s == null) {
        return null;
    }
String allowedChars="._-$,;~()/ ";
String urlEncoded = Uri.encode(url, allowedChars);

OK!

猜你喜欢

转载自blog.csdn.net/T_yoo_csdn/article/details/83411288