我有一个非常简单的服务,它调用一个URL并捕获由该服务编写的状态;
当我在浏览器中输入myServiceURL并打开时,它按预期工作并显示“OK”。
同一个服务的另一种方法已编写如下:
// Service call used to determine availability
System.Net.WebClient client = new System.Net.WebClient();
// I need this one (sorry, cannot disclose the actual URL)
Console.WriteLine(client.DownloadString(myServiceURL + ";ping"));
// I added this for test purposes
Console.WriteLine(client.DownloadString("https://www.google.com"));
我的代码中的"myServiceURL"使用"DownloadString"方法时,会抛出错误"The underlying connection was closed: An unexpected error occurred",但是在这一行没有任何Fiddler记录。然而,当我使用"DownloadString"方法访问google.com时,代码能够正常运行并输出控制台信息。
为了解决这个问题,我尝试了其他建议,包括设置UseDefaultCredentials、Encoding选项、添加适当的请求头等,但都没有任何改善。
client.UseDefaultCredentials = true;
client.Encoding = Encoding.UTF8;
当我在浏览器中输入myServiceURL并打开时,它按预期工作并显示“OK”。
同一个服务的另一种方法已编写如下:
// Request
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(myServiceURL + ";login");
// Set the request configuration options
req.Method = "POST";
req.ContentType = "text/xml";
req.ContentLength = bytes.Length;
req.Timeout = -1;
// Call for the request stream
using (Stream os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
}
// ....snip
// This line fails with the same error as before
WebResponse resp = req.GetResponse()
这一切都在运行 Windows 7 (64-bit) 电脑上,使用 .NET Framework 4.0;myServiceURL 上的服务是第三方服务,我无法控制。