0

我的网络请求有问题...

当我有一个无效的 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)。我没看到/明白。

4

1 回答 1

0

http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.begingetrequeststream.aspx

您忘记了一步,您也可以在请求对象上设置超时

一般的想法是您获取请求流,将您的请求“字符串”转换为二进制并将其提供给流。

然后你的响应回调触发你再次抓取流并将其转换回字符串。

此示例中的 postData 是您在发布请求中发送到服务器的内容。

于 2012-12-22T21:18:12.683 回答