炫意html5
最早CSS3和HTML5移动技术网站之一

使用HttpWebRequest 进行请求时出现不同的异常

下面两段代码返回的异常为什么不一样,有大佬解释一下吗?

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://www.alibabacloud.com");
request.Timeout = 5000;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
HttpWebRequest request2 = (HttpWebRequest) WebRequest.Create("https://www.cnblogs.com");
request2.Timeout = 1;
HttpWebResponse response2 = (HttpWebResponse) request2.GetResponse();

异常信息为

Unhandled Exception: System.Net.WebException: The operation has timed out.
at System.Net.HttpWebRequest.GetResponse()

第二段代码:

HttpWebRequest request = (HttpWebRequest) WebRequest.Create("https://www.alibabacloud.com");
request.Timeout = 5000;
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
request = (HttpWebRequest) WebRequest.Create("https://www.cnblogs.com");
request.Timeout = 1;
response = (HttpWebResponse) request.GetResponse();

异常信息为

Unhandled Exception: System.OperationCanceledException: The operation was canceled.
at System.Net.HttpWebRequest.GetResponse()

为什么返回的异常信息会不一样啊? 有哪些知识需要我去了解的吗?

还有一个问题就是同样的代码,windows上返回 timeout错误, linux上返回 operationcancel 错误??

回答

https://github.com/restsharp/RestSharp
第三方的库,封装的HttpWebRequest。

代码里 request2 设置的超时时间太短了,1毫秒。肯定报错。

炫意HTML5 » 使用HttpWebRequest 进行请求时出现不同的异常

Java基础教程Android基础教程