C#中的HttpUtility.UrlEncode编码与Java中URL编码不一致
最近需要调用JAVA程序接口,其中遇到的URL转码的2个问题:
1、Java中URL编码产生的字符是大写,而C#中的HttpUtility.UrlEncode产生的字符是小写;
2、Java中URL编码英文'(',')'是分别转成'%28'和 '%29',而C#中的HttpUtility.UrlEncode英文括号并没有转码。
所以两者生成的字符不一致,导致系统出错。
下面贴出解决方案:
// 对转码后的字符进行大写转换,不会把参数转换成大写 public static string UrlEncodeToJava(string source) { StringBuilder builder = new StringBuilder(); foreach (char c in source) { if (HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).Length > 1) { builder.Append(HttpUtility.UrlEncode(c.ToString(), Encoding.UTF8).ToUpper()); } else { builder.Append(c); } } string encodeUrl = builder.ToString().Replace("(", "%28").Replace(")", "%29"); return encodeUrl; }