1

I would like to check to see if URL given by the user is valid or not. Because if it is not, for example "http://www.stackoverflow" then it will crash the program later. I have tried to use the Web Response but it cannot find a definition for Irequest.GetResponse();

 try
            {
                string url = HomepageTextBox.Text;
                if (url != "")
                {
                    WebRequest Irequest = WebRequest.Create(url);
                    WebResponse Iresponse = Irequest.GetResponse();

                    if (Iresponse != null)
                    {

                    }
                }
                else
                {
                    HomepageTextBox.Text = "http://www.google.com";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Invalid URL");
            }

Thank you in advance :)

If you need any more details please comment and I will be happy to explain in further detail :)

user3795349
  • 314
  • 2
  • 16

1 Answers1

0

I remember having the same problem and after looking at the MSDN webpage I decided that it is incorrect. In WP8.0 there is no GetResponse(), but in WP8.1 there is GetResponseAsync().

So I decided to use HttpWebRequest instead and use BeginGetResponse/EndGetResponse -- and as far as I know you have to use a callback. Here's a simple example.


public void GetWebAddress(string web_address)
{
    HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(web_address);
    if (request != null) request.BeginGetResponse(MyHttpCallback, request);            
}

void MyHttpCallback(IAsyncResult result)
{
    HttpWebRequest request = result.AsyncState as HttpWebRequest;
    if (request != null)
    {
        try
        {
            // if you're using 8.1 try enclosing theses lines with "using"
            // there is no .Close()

            WebResponse response = request.EndGetResponse(result);

            StreamReader reader;
            reader = new StreamReader(response.GetResponseStream());

            string responseText = reader.ReadToEnd();
            // reponseText now contains the html/text of the page


            reader.Close();
            response.Close();
        }
        catch (WebException e)
        {
            // your errors are here, set your flags
            string error_string = e.Message;
        }
    }
}
Chubosaurus Software
  • 8,133
  • 2
  • 20
  • 26