对字符串进行编码解码

C#以UTF8编码格式为例:

1 //编码
2 ViewBag.FileURL = HttpUtility.UrlEncode(UriString, Encoding.UTF8);
3 //解码
4  FileURL = HttpUtility.UrlDecode(FileURL, UTF8Encoding.UTF8);

 JS:

encodeURI(URIstring)//把字符串作为 URI 进行编码
decodeURI(URIstring)//解码

escape是对字符串(string)进行编码(而另外两种是对URL)

encodeURI方法不会对下列字符编码  ASCII字母、数字、~!@#$&*()=:/,;?+'
encodeURIComponent方法不会对下列字符编码 ASCII字母、数字、~!*()'
所以encodeURIComponent比encodeURI编码的范围更大。
1、如果只是编码字符串,不和URL有半毛钱关系,那么用escape。
2、如果你需要编码整个URL,然后需要使用这个URL,那么用encodeURI。
比如
encodeURI("http://www.cnblogs.com/season-huang/some other thing");
编码后会变为
"http://www.cnblogs.com/season-huang/some%20other%20thing";

其中,空格被编码成了%20。但是如果你用了encodeURIComponent,那么结果变为

"http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2Fsome%20other%20thing"

看到了区别吗,连 "/" 都被编码了,整个URL已经没法用了。

3、当你需要编码URL中的参数的时候,那么encodeURIComponent是最好方法。

var param = "http://www.cnblogs.com/season-huang/"; //param为参数
param = encodeURIComponent(param);
var url = "http://www.cnblogs.com?next=" + param;
console.log(url) //"http://www.cnblogs.com?next=http%3A%2F%2Fwww.cnblogs.com%2Fseason-huang%2F"
看到了把,参数中的 "/" 可以编码,如果用encodeURI肯定要出问题,因为后面的/是需要编码的。
4、使用btoa和atob来进行Base64转码和解码
//解决中文编码异常
window.btoa(encodeURIComponent(str));
decodeURIComponent(window.atob(str));

 java:

1、url编码解码

URLEncoder.encode(str,"utf-8");//编码
URLDecoder.decode(str,"utf-8");//解码

 2、base64编码解码

String tokenId = new String(new BASE64Decoder().decodeBuffer(tokenIdByBase), "UTF-8");//解码
final BASE64Encoder encoder = new BASE64Encoder();
final String text = "字串文字";
final byte[] textByte = text.getBytes("UTF-8");
//编码
final String encodedText = encoder.encode(textByte);
原文地址:https://www.cnblogs.com/lijianda/p/7074697.html