0

I have some problem with my webrequest...

when I have an invalid url, my program hangs :/ I read on the internet that it has something to do with GetResponse and I have to use BeginGetResponse (async) ?

I tried various code with async, but does not work...

what I have (hangs with invalid url) :

            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();

What I tried:

    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);

But here I get an InvalidOperation exception (even with a valid/existed url). I don't see/get it.

keno
  • 93
  • 3
  • 11

1 Answers1

0

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

You forgot a step, Also you can set a timeout on the request object

General idea is you grab the request stream, convert your request "string" to binary and feed it to the stream.

Then your response callback fires where you grab the stream again and translate it back to a string.

postData in this example is what you are sending to the server in the post request.

Michael Christensen
  • 1,768
  • 1
  • 13
  • 11