---
title: "字符串的encode/escape"
author: "mingren135"
date: "2013-12-09T13:05:32Z"
tags: []
categories: ["移动开发"]
slug: "encode-escape"
draft: false
lastmod: "2013-12-09T16:12:04Z"
id: 1987197
url: "https://mingren135.iteye.com/blog/1987197"
---

遇到中文decode的问题，从cookie中拿到urlencode的值是中文，在urldecode时发现中文的最后1个字丢失，通过打日志最终定位到是字符编码的问题。

```
//不带charset参数的decode,不建议使用。。。
@Deprecated
public static String decode(String s)
Deprecated. The resulting string may vary depending on the platform's default encoding. Instead, use the decode(String,String) method to specify the encoding.
```

 

```
//带charset参数的decode
public static String decode(String s,
            String enc)
                     throws UnsupportedEncodingException
Decodes a application/x-www-form-urlencoded string using a specific encoding scheme. 
如果是utf-8编码的，则：String nick = URLDecoder.decode(nick, "UTF-8");
```

 

一、URLEncoder/URLDecoder：两个函数分别用于编码 URL 字符串和解码已编码的 URL 字符串，主要是实现对中文字符的编码，原理是把中文字符转换为十六进制并按某种规则进行字符串组合，实现字符的编码与解编码，保证URL数据传递过程中文字符的完整性和兼容性。

```
测试中文
-->
GB2312编码：%B2%E2%CA%D4%D6%D0%CE%C4
UTF-8编码：%E6%B5%8B%E8%AF%95%E4%B8%AD%E6%96%87
------------------------------------------------
~!@#$%^&*()_+|\\=-,./?><;'][{}\"
-->
%7E%21%40%23%24%25%5E%26%2A%28%29_%2B%7C%5C%3D-%2C.%2F%3F%3E%3C%3B%27%5D%5B%7B%7D%22
```

   
 二、escape/unescape：js有该方法，附件是对应java的实现

1）escape对String 对象编码以便它们能在所有计算机上可读

说明 ： escape 方法返回一个包含了charstring内容的字符串值（ Unicode 格式）。所有空格、标点、重音符号以 及 其他非 ASCII字符都用 %xx 编码代替，其中 xx 等于表示该字符的十六进制数。例如，空格返回的是"%20 " 。 字符值大于 255 的以 %uxxxx 格式存储。

注意 ：escape 方法不能够用来对统一资源标示码 (URI) 进行编码。对其编码应使用 encodeURI和encodeURIComponent 方法。 

 

2）unescape解码用 escape 方法进行了编码的 String 对象。 

说明 ： unescape 方法返回一个包含 charstring 内容的字符串值。所有以 %xx 十六进制形式编码的字符都用 ASCII 字符集中等价的字符代替。 以 %uxxxx 格式（Unicode 字符）编码的字符用十六进制编码 xxxx 的 Unicode 字符代替. 

注意 : unescape 方法不能用于解码统一资源标识码 (URI)。解该码可使用 decodeURI 和decodeURIComponent 方法。 

```
测试中文
-->
escape编码：%u6D4B%u8BD5%u4E2D%u6587
-------------------------------------
~!@#$%^&*()_+|\=-,./?><;'][{}"
-->
%7e%21%40%23%24%25%5e%26%2a%28%29%5f%2b%7c%5c%3d%2d%2c%2e%2f%3f%3e%3c%3b%27%5d%5b%7b%7d%22
```