c#实现php中的http_build_query功能
版权声明:
本文为博主原创文章,转载请声明原文链接...谢谢。o_0。
更新时间:
2017-08-19 10:42:48
温馨提示:
学无止境,技术类文章有它的时效性,请留意文章更新时间,如发现内容有误请留言指出,防止别人"踩坑",我会及时更新文章
首先添加程序集引用
var builder = new UriBuilder(); var query = HttpUtility.ParseQueryString(builder.Query); query["a"] = "tx g wh asdf"; query["b"] = "asdfasdfsadf"; string querystr=query.ToString().Trim('?');
输出结果
"a=tx+g+wh+asdf&b=asdfasdfsadf"
注意里面的空格转义成啦 +
其实上面是可以直接生成一个完整的url连接的,如下
var builder = new UriBuilder("http://example.com"); builder.Port =8080; var query = HttpUtility.ParseQueryString(builder.Query); query["a"] = "tx g wh asdf"; query["b"] = "asdfasdfsadf"; builder.Query = query.ToString(); string url = builder.ToString();
一个函数直接调用
public static string http_build_query(Dictionary<string,string> dict=null) { if (dict == null) { return ""; } var builder = new UriBuilder(); var query = HttpUtility.ParseQueryString(builder.Query); foreach (var item in dict.Keys) { query[item] = dict[item]; } return query.ToString().Trim('?'); }
使用方法
var param = new Dictionary<string, string> { {"a","this is a param" }, {"b","this second param"} }; var strrrrr = http_build_query(param);