作为与Open Invoice集成的一部分,该API需要一个遗留的Multipart/mixed:边界=“MIME-边界”请求标头。在互联网上使用这个头文件用于C#的文档非常少,包括微软文档。
POST请求中的两个文档包括一个UTF-8XML字符串和一个Base64 pdf字符串。出站请求需要Content-Type headers (每个文档一个),而HTTPRequestMessage本身并不支持,因为它假定您将传递一个“文本/纯文本”请求。
Headers.Add() //设置Content-Type时抛出异常
Headers.TryAddWithoutValidation() //没有解决这个问题
此外,请求需要使用请求正文的HMAC散列进行签名。
如何在C#中构建此请求?
发布于 2021-06-10 07:19:20
构建客户端
X509Certificate2 cert = new X509Certificate2(certificateName, certPassword);
var handler = new WebRequestHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ClientCertificates.Add(cert);
HttpClient client = new HttpClient(handler);
client.BaseAddress = new Uri(openInvoiceURL);构建请求
//Starting from byte[] for both files
var xmlString = System.Text.Encoding.UTF8.GetString(xmlBytes);
string pdf64 = Convert.ToBase64String(pdfBytes);
string url = "/docp/supply-chain/v1/invoices";
var multiPartContent = new MultipartContent("mixed", "_MIME-Boundary");
var xmlHttpContent = new StringContent(xmlString);
xmlHttpContent.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
multiPartContent.Add(xmlHttpContent);
var pdfHttpContent = new StringContent(pdf64);
pdfHttpContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
pdfHttpContent.Headers.Add("content-transfer-encoding", "base64");
pdfHttpContent.Headers.Add("Content-ID", pdfName);
multiPartContent.Add(pdfHttpContent);
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Content = multiPartContent;
request = AttachHMAC(request, secretKey);
var response = client.SendAsync(request).Result;
var responseString = response.Content.ReadAsStringAsync().Result;对请求正文进行签名(仅在发布时)
private HttpRequestMessage AttachHMAC(HttpRequestMessage request, string secretKey)
{
var payload = string.Empty;
if(request != null && request.Content != null)
{
payload = request.Content.ReadAsStringAsync().Result;
}
var hashMaker = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var payloadByteArray = Encoding.UTF8.GetBytes(payload);
byte[] hash = hashMaker.ComputeHash(payloadByteArray);
var base64Hash = Convert.ToBase64String(hash);
request.Headers.Add("mac", base64Hash);
return request;
}https://stackoverflow.com/questions/67912760
复制相似问题