【发布时间】:2017-11-02 14:42:55
【问题描述】:
我正在向 UPS 网站发送 xml 数据,有时我收到响应,有时我收到 异常:底层连接已关闭
查看将 xml 发送到特定 UPS url 的示例代码。
public ShippingAcceptResult ShippingAccept(string acceptDigestCode)
{
string strXml = "";
try
{
xmlRequest = new System.Xml.XmlDocument();
xmlRequest.LoadXml(@"<?xml version=""1.0""?>
<ShipmentAcceptRequest>
<Request>
<TransactionReference>
<CustomerContext>TR01</CustomerContext>
<XpciVersion>1.0001</XpciVersion>
</TransactionReference>
<RequestAction>ShipAccept</RequestAction>
<RequestOption>01</RequestOption>
</Request>
<ShipmentDigest>" + acceptDigestCode + "</ShipmentDigest></ShipmentAcceptRequest>");
byte[] bb = new System.Text.ASCIIEncoding().GetBytes(string.Format(XML_CONNECT, sAccessCode.Trim(), sUserId.Trim(), sPassword.Trim()));
byte[] bResponse = null;
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.Write(bb, 0, bb.Length);
xmlRequest.Save(ms);
bb = ms.ToArray();
xmlRespone = new XmlDocument();
string serverName = (testMode) ? "wwwcie" : "onlinetools.ups.com";
serverName = string.Format(UPS_SERVICE_URL, serverName, ShipRequestTypes.ShipAccept);
using (var client = new NoKeepAlivesWebClient())
{
bResponse = client.UploadData(serverName, "POST", bb);
}
if (bResponse != null)
{
xmlRespone.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(bResponse));
}
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("ShippingAccept " + ex.Message);
System.Windows.Forms.MessageBox.Show(strXml);
}
return new ShippingAcceptResult(xmlRespone);
}
public class NoKeepAlivesWebClient : WebClient
{
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address);
if (request is HttpWebRequest)
{
((HttpWebRequest)request).KeepAlive = false;
}
return request;
}
}
在我没有set KeepAlive = false 之前,我也收到了相同的错误消息,但现在当我设置KeepAlive = false 时,有时也会出现相同的连接关闭相关错误。
告诉我错误是特定于任何电脑的吗?
我应该像 KeepAlive 选项那样为 webclient 设置超时值吗?
所以请有人把我带到正确的方向来摆脱这个错误。
告诉我发生错误的所有可能原因。谢谢
【问题讨论】:
-
也许堆栈跟踪将有助于找到答案。
-
如果是 https,请确保您接受证书(编辑),不要等待,如果它有时有效,但其他人无法访问相同的 url,请忽略它
标签: c# xml webclient xmldocument ups