如何将XML编码到base64,然后将其保存到流中



任务是发送一个HTTPweb request以及必须转换为base64Soap Envelope

不幸的是,我无法将Envelope转换为base64,因为我的方法InsertSoapEnvelopeIntoWebRequest使用XML并将其保存到stream,如下所示。我需要按照这个结构来请求工作。

XmlDocument soapEnvelopeXml = CreateSoapEnvelope(attachmentName);
HttpWebRequest webRequest = CreateWebRequest(url, action, attachmentName);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
private static XmlDocument CreateSoapEnvelope(string attachmentName)
{
//Convert name to base64
var fileNameEncoded = EncodeStringToBase64(attachmentName);
var authorizationIdEncoded = EncodeStringToBase64("C61582-B73K47EJ54");
var authorizationKeyEncoded = EncodeStringToBase64("TWTXBP-HNEZ9J-74EV8Z-QM5J9T");
XmlDocument soapEnvelopeDocument = new XmlDocument();
soapEnvelopeDocument.LoadXml($@"<?xml version=""1.0"" encoding=""UTF-8""?><SOAP-ENV:Envelope xmlns:SOAP-ENV=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:SOAP-ENC=""http://schemas.xmlsoap.org/soap/encoding/"" SOAP-ENV:encodingStyle=""http://schemas.xmlsoap.org/soap/encoding/"" xmlns:ns4=""https://efaktura.bg/soap/""><SOAP-ENV:Body><ns4:uploadFile><ns4:authorizationId>{authorizationIdEncoded}</ns4:authorizationId><ns4:authorizationKey>{authorizationKeyEncoded}</ns4:authorizationKey><ns4:fileName>{fileNameEncoded}</ns4:fileName></ns4:uploadFile></SOAP-ENV:Body></SOAP-ENV:Envelope>");
//            doc.LoadXml(soapRequest.ToString());
return soapEnvelopeDocument;
}
public static string EncodeStringToBase64(string plainTextBytes)
{
var plainText = System.Text.Encoding.UTF8.GetBytes(plainTextBytes);
return System.Convert.ToBase64String(plainText);
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}

我曾尝试将XML转换为String,但在CreateSoapEnvelope中,我有一个方法LoadXML,如果它是base64,则该方法无法读取它,因为它不是XML格式。

如果我在InsertSoapEnvelopeIntoWebRequest中进行转换,则我无法使用soapEnvelopeXml.Save(stream)

我可以在哪里以及如何进行转换?

将InsertSoapEnvelope方法更改为:

private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
soapEnvelopeXml.WriteTo(tx);
string str = sw.ToString();
Console.WriteLine(soapEnvelopeXml.ToString());
ASCIIEncoding Encode = new ASCIIEncoding();
var arr = Encode.GetBytes(EncodeStringToBase64(str));
stream.Write(arr, 0, arr.Length);
}
}

如果你Console.WritelineXML.ToString(),它会给你参考。其思想是将XML写入使用StringWriterTextWriter。完成此操作后,必须先将其encode,然后将其转换为byte array。这只是一个写在小溪里的问题。您将数组、0偏移量和字节数组的长度作为参数。

最新更新