0

我有一串文本需要先转换为 base64,然后才能发布到 url。这是我的代码

  HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
      byte[] postDataBytes = Encoding.UTF8.GetBytes(strCXML);
       string returnValue = System.Convert.ToBase64String(postDataBytes);
       req.Method = "POST";
       req.ContentLength = postDataBytes.Length;
       req.ContentLength = postDataBytes.Length;
       Stream requestStream = req.GetRequestStream();
       requestStream.Write(returnValue,0, postDataBytes.Length);

问题是我在最后一行出现错误 System.IO.Stream.Write(byte[],int,int) returnValue is base64 string cant be used as byte[] required in stream.writer 知道如何使用那个base64字符串调用 returnvalue 并将其放入 url 谢谢

4

2 回答 2

4

您应该通过 Encoding.GetBytes 将 base64 字符串转换为字节数组

HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
byte[] postDataBytes = Encoding.UTF8.GetBytes(strCXML);
string returnValue = System.Convert.ToBase64String(postDataBytes);

postDataBytes = Encoding.UTF8.GetBytes(returnValue);

req.Method = "POST";
req.ContentLength = postDataBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postDataBytes, 0, postDataBytes.Length);
于 2012-10-09T23:10:52.443 回答
0

您正在使用 Stream 作为您的 requestStream。Stream.Write 采用字节数组,而不是 Base64 字符串。

我认为您的操作顺序错误。我会先将 strCXML 转换为 Base64 字符串,然后将其编码为字节数组以写入请求流。

于 2012-10-09T23:09:43.087 回答