最近与建行接口做对接和与一家短信运营商做对接时候遇到了这个坑
在java中对UrlEncode 时候哪些url非安全字符被转为%数字和大写字幕组合,比如:zhangsan/d 会被转为 zhangsan%2Fd ,而在C#中确被转为 zhangsan%2fd 。注意大小写的差异
然后就导致了各种加密验签无法通过的情况。
于是就自己在C#原来的UrlEncode的基础上写了一个UrlEncode方法
1/// <summary> 2 /// Url编码 3 /// </summary> 4 /// <param name="str">原字符串</param> 5 /// <param name="encoding">编码格式</param> 6 /// <param name="upper">特殊字符编码为大写</param> 7 /// <returns></returns> 8 static string UrlEncode(string str, Encoding encoding) 9 { 10 11 if (encoding == null) 12 { 13 encoding = UTF8Encoding.UTF8; 14 } 15 byte[] bytes = encoding.GetBytes(str); 16 int num = 0; 17 int num2 = 0; 18 19 for (int i = 0; i < bytes.Length; i++) 20 { 21 char ch = (char)bytes[i]; 22 if (ch == ' ') 23 { 24 num++; 25 } 26 else if (!IsUrlSafeChar(ch)) 27 { 28 num2++; //非url安全字符 29 } 30 } 31 32 if (num == 0 && num2 == 0) 33 { 34 return str; //不包含空格和特殊字符 35 } 36 37 byte[] buffer = new byte[bytes.Length + (num2 * 2)]; //包含特殊字符,每个特殊字符转为3个字符,所以长度+2x 38 int num3 = 0; 39 for (int j = 0; j < bytes.Length; j++) 40 { 41 byte num6 = bytes[j]; 42 char ch2 = (char)num6; 43 if (IsUrlSafeChar(ch2)) 44 { 45 buffer[num3++] = num6; 46 } 47 else if (ch2 == ' ') 48 { 49 buffer[num3++] = 0x2B; //0x2B代表 ascii码中的+,url编码时候会把空格编写为+ 50 } 51 else 52 { 53 //特殊符号转换 54 buffer[num3++] = 0x25; //代表 % 55 buffer[num3++] = (byte)IntToHex((num6 >> 4) & 15); //8位向右移动四位后 与 1111按位与 ,即保留高前四位 ,比如 /为 2f,则结果保留了2 56 buffer[num3++] = (byte)IntToHex(num6 & 15); //8位 ,与00001111按位与,即保留 后四位 ,比如 /为2f,则结果保留了 f 57 58 } 59 } 60 61 return encoding.GetString(buffer); 62 63 64 65 } 66 67 static bool IsUrlSafeChar(char ch) 68 { 69 if ((((ch < 'a') || (ch > 'z')) && ((ch < 'A') || (ch > 'Z'))) && ((ch < '0') || (ch > '9'))) 70 { 71 72 switch (ch) 73 { 74 case '(': 75 case ')': 76 case '*': 77 case '-': 78 case '.': 79 case '!': 80 break; //安全字符 81 82 case '+': 83 case ',': 84 return false; //非安全字符 85 default: //非安全字符 86 if (ch != '_') 87 { 88 return false; 89 } 90 break; 91 } 92 } 93 return true; 94 } 95 96 static char IntToHex(int n) //n为0-f 97 { 98 if (n <= 9) 99 { 100 return (char)(n + 0x30); //0x30 十进制是48 对应ASCII码是0 101 } 102 return (char)((n - 10) + 0x41); //0x41 十进制是 65 对应ASCII码是A 103 }