C#Web客户端异常:基础连接已关闭

时间:2017-10-31 14:06:37

标签: c# webclient

当我的下面的代码正在执行时,我得到的一些时间底层连接已关闭异常并且根元素丢失。

public ShippingAcceptResult ShippingAccept(string acceptDigestCode)
{
    requestType = ShipRequestTypes.ShipAccept;

    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()));

    System.IO.MemoryStream ms = new System.IO.MemoryStream();
    ms.Write(bb, 0, bb.Length);
    xmlRequest.Save(ms);
    bb = ms.ToArray();
    System.Net.WebClient wc = new System.Net.WebClient();
    xmlRespone = new XmlDocument();
    //System.Web.HttpContext.Current.Response.Write(System.Text.ASCIIEncoding.ASCII.GetString(wc.UploadData(UPS_URL, "POST", bb)));
    string serverName = (testMode) ? "wwwcie" : "www";

    serverName = string.Format(UPS_SERVICE_URL, serverName, ShipRequestTypes.ShipAccept);
    xmlRespone.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(wc.UploadData(serverName, "POST", bb)));
    //xmlRespone.Save(@"d:\shippingresponseAccept.xml");
    return new ShippingAcceptResult(xmlRespone);
}

所以我搜索谷歌并发现很少有SO链接。他们告诉我设置KeepAlive = false;并且我做了。这是我从中获取帮助的网址https://stackoverflow.com/a/24719999/728750

我还检查了其他几个SO链接,他们说增加超时。那些网址是

https://stackoverflow.com/a/6994391/728750 https://stackoverflow.com/a/3052637/728750 https://stackoverflow.com/a/1530717/728750

var request = (HttpWebRequest)WebRequest.Create(remoteUri);
request.Timeout = 30000;

所以我只需要知道我是否设置KeepAlive = false;是否足够,或者我还需要设置 Timeout以及KeepAlive

请指导我。感谢

0 个答案:

没有答案