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

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

Hi, works like a charm.
thank you.

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... ?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.