1

错误:您必须在调用 [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())
4

3 回答 3

1

简而言之: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());
    }
  }
}
于 2013-09-03T16:21:35.597 回答
1

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

于 2013-09-03T16:22:11.330 回答
0

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

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

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

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

于 2018-10-18T16:51:22.203 回答