c#实现php的http_build_query功能

php的http_build_query不得不说很好用,用c#实现它,过程稍长

http_build_query方法:

public static string http_build_query(Dictionary<string, string> dict = null)
{
if (dict == null)
{
return "";
}
string QueryString=string.Empty;

foreach (KeyValuePair<string, string> kvp in dict)
{
QueryString = QueryString + System.Net.WebUtility.UrlEncode(kvp.Key) + "=" + System.Net.WebUtility.UrlEncode(kvp.Value) + "&";
}
QueryString = QueryString.Substring(0, QueryString.Length - 1);
return QueryString;
}

调用过程:

protected void testhttp_build_query_Click(object sender, EventArgs e)
{
try
{
string secret = "1e7f7231-12b1-86ec"; //密钥
var DataDictionary = new Dictionary<string, string>();
DataDictionary.Add("currency", "HKD");
DataDictionary.Add("amount", "100");
DataDictionary.Add("return_url", "www.baidu.com/api"); //显示支付成功的界面,应该做多一个页面叫payment_return.aspx
DataDictionary.Add("customer_first_name", "stephen");
DataDictionary.Add("customer_last_name", "");
DataDictionary.Add("customer_address", "");
DataDictionary.Add("customer_phone", "90472886");
DataDictionary.Add("customer_email", "");
DataDictionary.Add("customer_state", "");
DataDictionary.Add("customer_country", "CN");
DataDictionary.Add("network", "alipay");
DataDictionary.Add("subject", "Jiyun Fee");
Dictionary<string, string> dic_SortedByKey = DataDictionary.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value); //对key排从小到大的升序,类似php ksort($fields);
var strrrrr = http_build_query(dic_SortedByKey);

showDesString.Text = strrrrr;
}
catch (Exception err)
{
Response.Write(err.Message);
}
}

修正下,不要使用HttpUtility.UrlEncode做Urlencode,因为它转出来的是小写,应该使用System.Net.WebUtility.UrlEncode,而java,php使用urlencode转化出来的是大写,

 

 我是原著stephendeng,转载请说明

posted @ 2021-03-11 20:22  AlanNever  阅读(329)  评论(0编辑  收藏  举报