如何解决HTTP Web Request底层连接被关闭错误调用API?

时间:2018-01-30 08:37:59

标签: c# api asp.net-web-api httpwebrequest ups

我正在尝试使用UPS API验证带有City的zipCode " https://www.ups.com/ups.app/xml/AV"

以下是我的代码

string xmlRequest = "<?xml version=\"1.0\"?>" +
                "<AccessRequest>" +
                "<AccessLicenseNumber>xxxx</AccessLicenseNumber>" +
                "<UserId>xxx</UserId>" +
                "<Password>xxx</Password>" +
                "</AccessRequest>" +
                "<?xml version=\"1.0\"?>" +
                "<AddressValidationRequest xml:lang=\"en-US\">" +
                "<Request>" +
                "<TransactionReference>" +
                "<CustomerContext>Customer Data</CustomerContext>" +
                "<XpciVersion>1.0001</XpciVersion>" +
                "</TransactionReference>" +
                "<RequestAction>AV</RequestAction>" +
                "</Request>" +
                "<Address>" +
                "<PostalCode>" + "38305" + "</PostalCode>" +
                "<City>" + "TENNESSEE" + "</City>" +
                "</Address>" +
                "</AddressValidationRequest>";
                string url = "https://www.ups.com/ups.app/xml/AV";

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                //ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;


                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(xmlRequest);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencode";
                req.ContentLength = requestBytes.Length;
//                req.KeepAlive = false;

                //req.UseDefaultCredentials = true;
  //              req.UserAgent = "Patoooey";
                Stream requestStream = req.GetRequestStream();                
                requestStream.Write(requestBytes, 0, requestBytes.Length);
                requestStream.Close();
                HttpWebResponse res = (HttpWebResponse)req.GetResponse();

                StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
                string backstr = sr.ReadToEnd();

它在我的本地计算机上运行正常。但是当我在实时服务器上部署它时。它给出了错误 基础连接已关闭:接收时发生意外错误._____    在System.Net.HttpWebRequest.GetRequestStream(TransportContext&amp; context)    在System.Net.HttpWebRequest.GetRequestStream()

我尝试将ServicePointManager.SecurityProtocol设置为TLS,TLS11或TLS12 但没有什么工作在实时服务器上。 还尝试了request.KeepAlive = false,request.UseDefaultCredentials = true 和request.UserAgent to&#34;任何大于5 char&#34;。

的单词

服务器正在运行Windows Server数据中心SP2 我们将不胜感激。 感谢

1 个答案:

答案 0 :(得分:0)

  • 即使我遇到了同样的问题,也可以通过设置以下代码来解决  ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; .net默认情况下会选择服务器中存在的最高安全协议
  • 稍后有详细的了解,请参考以下内容,以作解释 Default SecurityProtocol in .NET 4.5