秘钥标签验证-生成秘钥
1、出错地方
因为用转译后的编码生成签名秘钥导致请求一直失败;
解决办法:用原报文XML先 生成签名秘钥;传给接口用xml转译后;
public static string GetHttpPostByAdds(string Url, string sendXml, string custID) { //解决 SSL/TLS 安全通道问题 System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //转译报文 string sendInfo = HttpUtility.UrlEncode(sendXml, Encoding.GetEncoding("utf-8")); string resultStr = string.Empty; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); request.Method = "POST"; request.Timeout = 10000; request.ContentType = "application/x-www-form-urlencoded"; //获取签名用原报文的 string signValue = GetSign(sendXml, "123456"); request.Headers.Add("serverName", "orderStatus"); request.Headers.Add("CustID", custID); request.Headers.Add("sign", signValue); string contentStr = $"serverName=orderStatus&CustID={custID}&sign={signValue}&content={sendInfo}";// request.Headers.Add("content", contentStr); byte[] data = Encoding.GetEncoding("utf-8").GetBytes(contentStr); request.ContentLength = data.Length; Stream myRequestStream = request.GetRequestStream(); myRequestStream.Write(data, 0, data.Length); myRequestStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream(); StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));// resultStr = myStreamReader.ReadToEnd(); myStreamReader.Close(); myResponseStream.Close(); } catch (WebException ex) { var errorSr = new StreamReader(ex.Response.GetResponseStream()); resultStr = errorSr.ReadToEnd(); } return resultStr; } /// <summary> /// 获取签名 /// </summary> public static string GetSign(string content, string key) { string value = GetMd5(content + key); byte[] bytes = Encoding.GetEncoding("utf-8").GetBytes(value); return Convert.ToBase64String(bytes); } public static string GetMd5(string plaintextValue) { MD5 md = MD5.Create(); byte[] t = md.ComputeHash(Encoding.GetEncoding("utf-8").GetBytes(plaintextValue)); StringBuilder sb = new StringBuilder(); for (int i = 0; i < t.Length; i++) { sb.Append(t[i].ToString("x").PadLeft(2, '0')); } return sb.ToString(); }