我的网络请求有问题...
当我有一个无效的 url 时,我的程序挂起:/ 我在互联网上读到它与它有关GetResponse
并且我必须使用BeginGetResponse
(async) ?
我尝试了各种异步代码,但不起作用......
我有什么(挂起无效的网址):
WebRequest request;
request = WebRequest.Create(url);
WebResponse webResponse = request.GetResponse();
Stream ReceiveStream = webResponse.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(ReceiveStream, encode);
reader = new XmlTextReader(readStream);
String[] login = new String[1];
reader.Read();
reader.ReadStartElement("response");
reader.ReadStartElement("item");
login[0] = reader.ReadString();
reader.ReadEndElement();
reader.ReadEndElement();
reader.Close();
我尝试了什么:
private HttpWebResponse response;
private void FinishWebRequest(IAsyncResult result)
{
response = (result.AsyncState as HttpWebRequest).EndGetResponse(result) as HttpWebResponse;
}
public void Read()
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(FinishWebRequest), request);
Stream ReceiveStream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader readStream = new StreamReader(ReceiveStream, encode);
reader = new XmlTextReader(readStream);
但在这里我得到一个InvalidOperation
例外(即使有一个有效/现有的 url)。我没看到/明白。