如何使用HttpClient将哈希值作为头部发送?
如何使用HttpClient将哈希值作为头部发送?
我正在尝试将支付平台集成到我的Web应用程序中,但查询交易的一个要求是使用GET请求将哈希值(某些变量的哈希值)作为标题发送。这是我尝试过的方法:
string hashcode = "3409877" + "117" + "D3D1D05AFE42AD508"; var hashedBytes = SHA512.Create().ComputeHash(Encoding.UTF8.GetBytes(hashcode)); // 获取哈希字符串。 var hash = BitConverter.ToString(hashedBytes).Replace("-", "").ToLower(); hash = hash.ToString().ToUpper(); var amount_kobo = Convert.ToInt32(model.TransactionAmount * 100); string url = "https://sandbox.interswitchng.com/collections/api/v1/gettransaction.json?productid=117&transactionreference=" + model.TransactionReference + "&amount=" + amount_kobo; using (var client = new HttpClient()) { #if DNX451 // 忽略服务器证书错误 //ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; #elif DNXCORE50 // 目标DNX没有实现 #endif client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("text/html")); client.DefaultRequestHeaders.Add("Hash",hash); HttpResponseMessage response = await client.GetAsync(url); string responsestr = ""; if (response.IsSuccessStatusCode) { responsestr = await response.Content.ReadAsStringAsync(); return Json(new { success = true, response = responsestr, hash = hash }); } }
但是我的哈希值没有发送,当我发送请求后检查浏览器时,我看不到我的哈希标题,而且我应该将标题作为哈希类型发送,但我不知道该怎么做。
我尝试将这一行改为:
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("hash"));
但仍然不起作用。
更新
这是浏览器中请求头的截图
看起来我的标题根本没有发送。
问题出现的原因是在将哈希值转换为字符串后,字符串中可能包含在GET请求中发送受限制的字符。因此,在发送之前,应该考虑使用Uri.EscapeDataString()函数对字符串进行编码。
解决方法之一是使用Uri.EscapeDataString()函数对字符串进行编码:
hash = Uri.EscapeDataString(hash);
另一种解决方法是将hashedBytes转换为Base64,并在其后面仅对几个符号进行编码。可以通过以下链接获取有关如何进行Base64编码和URL安全编码的更多信息:
- [convert](https://stackoverflow.com/questions/11634237)
- [encode](https://stackoverflow.com/questions/26353710)