在调用[Begin]GetResponse之前,必须将ContentLength字节写入请求流



错误:在调用[Begin]GetResponse之前,必须将ContentLength字节写入请求流。

有人能告诉我为什么在运行以下代码时会出现上述错误吗

        Dim xml As New System.Xml.XmlDocument()
        Dim root As XmlElement
        root = xml.CreateElement("root")
        xml.AppendChild(root)
        Dim username As XmlElement
        username = xml.CreateElement("UserName")
        username.InnerText = "xxxxx"
        root.AppendChild(username)
        Dim password As XmlElement
        password = xml.CreateElement("Password")
        password.InnerText = "xxxx"
        root.AppendChild(password)
        Dim shipmenttype As XmlElement
        shipmenttype = xml.CreateElement("ShipmentType")
        shipmenttype.InnerText = "DELIVERY"
        root.AppendChild(shipmenttype)

        Dim url = "xxxxxx"
        Dim req As WebRequest = WebRequest.Create(url)
        req.Method = "POST"
        req.ContentType = "application/xml"
        req.Headers.Add("Custom: API_Method")
        req.ContentLength = xml.InnerXml.Length
        Dim newStream As Stream = req.GetRequestStream()
        xml.Save(newStream)
        Dim response As WebResponse = req.GetResponse()

        Console.Write(response.ToString())

可能是xml.InnerXml的字符长度与xml.Save(newStream)中实际写入流的内容之间的长度不匹配。例如,检查InnerXml是否包括xml版本节点。此外,我看不到您指定了字符编码,这肯定会影响导线的大小。也许您需要保存到一个临时内存流中,获取其长度,然后在请求中发送。

简而言之:newStream.Length != xml.InnerXml.Length

  • 首先,XmlDocument.Save(Stream)将对响应进行编码,这可能导致与.InnerXml字符串中的字符数不同的字节数
  • .InnerXML不一定包含其他内容,例如XML前导

下面是一个完整的例子。(对不起,我的VB有点生疏,所以改为C#):

using System;
using System.IO;
using System.Net;
using System.Xml;
namespace xmlreq
{
  class Program
  {
    static void Main(string[] args)
    {
      var xml = new XmlDocument();
      var root = xml.CreateElement("root");
      xml.AppendChild(root);
      var req = WebRequest.Create("http://stackoverflow.com/");
      req.Method = "POST";
      req.ContentType = "application/xml";
      using (var ms = new MemoryStream()) {
        xml.Save(ms);
        req.ContentLength = ms.Length;
        ms.WriteTo(req.GetRequestStream());
      }
      Console.WriteLine(req.GetResponse().Headers.ToString());
    }
  }
}

我今天遇到了这个错误,问题是端点提供商多年来一直将http请求重定向到https,但更改了他们的策略。所以从更新我的代码

request = WebRequest.Create("http://api.myfaxservice.net/fax.php") 

request = WebRequest.Create("https://api.myfaxservice.net/fax.php")

成功了。如果提供商关闭http,我想这将是一个更容易运行的问题,因为这个错误让我走错了路。

相关内容

  • 没有找到相关文章

最新更新