C# 如何实现URL编码?

经常我们在模拟HTTP请求的时候,需要对提交的参数进行URL编码。 在这里我们通过实现一个简单的扩展方法来完成这个功能~

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
public static class StringExplend
{
    public static string ToURLEncoding(this string value)
    {
        if(!string.IsNullOrEmpty(value)
        {
            byte[] _strBytes = Encoding.UTF8.GetBytes(value);
            StringBuilder _sb = new StringBuilder();
            foreach(var item in _strBytes)
            {
                _sb.Append(@"%",Convert.ToString(item,16));
                // 当然在这里也可以使用
                // _sb.Append(@"%" + item.ToString("x2"));
            }
            return _sb.ToString();
        }else return string.Empty;
    }
}

注意,这个方法有一个弊端,就是会将英文字符也进行转换,所以你需要手动过滤掉英文/数字。这里建议你选择使用在 System.Web 命名空间下的 HttpUtility 对象,使用方法很简单,如下:

1
2
3
4
public string URL_Encoding(string srcText, Encoding encoding)
{
       return HttpUtility.UrlEncode(srcText, encoding);
}
Built with Hugo
主题 StackJimmy 设计