You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
82 lines
3.0 KiB
82 lines
3.0 KiB
using System.Collections.Generic;
|
|
using System.Text;
|
|
using System.Security.Cryptography;
|
|
using System.Web;
|
|
|
|
namespace Jd.ACES.Utils
|
|
{
|
|
public class WebUtils
|
|
{
|
|
/// <summary>
|
|
/// 给Jd请求签名。
|
|
/// </summary>
|
|
/// <param name="parameters">所有字符型的Jd请求参数</param>
|
|
/// <param name="secret">签名密钥</param>
|
|
/// <param name="qhs">是否前后都加密钥进行签名</param>
|
|
/// <returns>签名</returns>
|
|
public static string SignJdRequest(IDictionary<string, string> parameters, string secret, bool qhs)
|
|
{
|
|
// 第一步:把字典按Key的字母顺序排序
|
|
IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
|
|
IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
|
|
|
|
// 第二步:把所有参数名和参数值串在一起
|
|
StringBuilder query = new StringBuilder(secret);
|
|
while (dem.MoveNext())
|
|
{
|
|
string key = dem.Current.Key;
|
|
string value = dem.Current.Value;
|
|
if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
|
|
{
|
|
query.Append(key).Append(value);
|
|
}
|
|
}
|
|
if (qhs)
|
|
{
|
|
query.Append(secret);
|
|
}
|
|
// 第三步:使用MD5加密
|
|
MD5 md5 = MD5.Create();
|
|
byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
|
|
|
|
// 第四步:把二进制转化为大写的十六进制
|
|
StringBuilder result = new StringBuilder();
|
|
for (int i = 0; i < bytes.Length; i++)
|
|
{
|
|
result.Append(bytes[i].ToString("X2"));
|
|
}
|
|
|
|
return result.ToString();
|
|
}
|
|
/// <summary>
|
|
/// 组装普通文本请求参数。
|
|
/// </summary>
|
|
/// <param name="parameters">Key-Value形式请求参数字典</param>
|
|
/// <returns>URL编码后的请求数据</returns>
|
|
public static string BuildQuery(IDictionary<string, string> parameters)
|
|
{
|
|
StringBuilder postData = new StringBuilder();
|
|
bool hasParam = false;
|
|
|
|
IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
|
|
while (dem.MoveNext())
|
|
{
|
|
string name = dem.Current.Key;
|
|
string value = dem.Current.Value;
|
|
// 忽略参数名或参数值为空的参数
|
|
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
|
|
{
|
|
if (hasParam)
|
|
{
|
|
postData.Append("&");
|
|
}
|
|
postData.Append(name);
|
|
postData.Append("=");
|
|
postData.Append(HttpUtility.UrlEncode(value, Encoding.UTF8));
|
|
hasParam = true;
|
|
}
|
|
}
|
|
return postData.ToString();
|
|
}
|
|
}
|
|
}
|
|
|