0

Hi
I attached here a code that i have a problem with.
the function CheckStatusCode() suppose to connect to uri and check the http response status.
it should display on the screen the status received. usually the status is "OK" (200). but for instance if the page doesn't exist the status should be "NOT FOUND" (404).
the function works fine with uri that returns status 200.
in any other status, i.e 404, the method throws exception.
basically i can parse the the exception message and understand the status from there, but i don"t see a reason to do so.

please help me understand why i'am getting exception and the function doesn't do what it supposed to do.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Windows.Forms;
using System.IO;
namespace Configurator
{
    class Navigation
    {
        public void CheckStatusCode()
        {
            HttpWebRequest request=null;
            HttpWebResponse response=null;
            try
            {
                request = (HttpWebRequest)WebRequest.Create("http://www.ynet.co.il");//OK 200
                //request = (HttpWebRequest)WebRequest.Create("https://yedion.afeka.ac.il/yedion/dxcbfgdfsg");//NOT FOUND 404
                response = (HttpWebResponse)request.GetResponse();
                MessageBox.Show(response.StatusCode.ToString());
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);

            }

            finally
            {
                response.Close();
            }
        }
    }
}

Edited by igalbk: mistake

3
Contributors
3
Replies
11
Views
7 Years
Discussion Span
Last Post by honeyxyz
0

Have a look,

public class TestIt
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("http://www.sample.com/index1.php");
        try
        {
            using (WebResponse response = request.GetResponse())
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Console.WriteLine(httpResponse.StatusCode);
            }
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse)response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                {
                    string text = new StreamReader(data).ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
    }
}
0

good for start... can u give some breaf for post data on other server, and get responce from them and how to access thoes data in our application... ?

This article has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.