错误: 在调用[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())
答案 0 :(得分: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());
}
}
}
答案 1 :(得分:1)
xml.InnerXml
的字符长度与实际写入xml.Save(newStream)
中的流的长度不匹配。例如,检查InnerXml
是否包含xml版本节点。另外,我没有看到你指定一个字符编码,这肯定会影响线路上的大小。也许您需要保存到临时内存流,获取其长度,然后在请求中发送它。
答案 2 :(得分:0)
我今天遇到此错误,问题是端点提供程序将HTTP请求重定向到https已有多年了,但是更改了其策略。因此,从
更新我的代码request = WebRequest.Create("http://api.myfaxservice.net/fax.php")
到
request = WebRequest.Create("https://api.myfaxservice.net/fax.php")
成功了。如果提供者只是关闭http,我认为这将是一个更容易解决的问题,因为此错误使我误入歧途。