WebRequest and WebResponse classes are part of the System.Net namespace and the System.Net.Requests.dll and System.dll assemblies.They are used on the client for connecting to a server using HTTP or FTP protocol.
WebClient encapsulates the WebRequest and WebResponse classes and so makes it easier to work with the WebRequest and WebResponse classes.
HttpClient class is used for working with HTTP based services such as WebAPI.HttpClient includes many async methods such as GetAsync(Uri) and PostAsync(String, HttpContent).It is part of the System.Net.Http namespace.
To access a URL and fetch response using WebRequest and WebResponse classes follow the below steps:
1.Create an instance of the WebRequest object.Normally Create() method with URL as the argument is used to create an instance of WebRequest derived class.Since WebRequest is an abstract class so a derived class of WebRequest such as HttpWebRequest is used.
WebRequest reqObj = WebRequest.Create("http://www.example.com");
If you see the value of the reqObj at runtime you can see that it includes lots of useful properties:
If you see the type of the reqObj you will get the following response showing that the type of reqObj is HttpWebRequest.
{Name = “HttpWebRequest” FullName = “System.Net.HttpWebRequest”}
2.Once the WebRequest instance is created call the GetResponse() method using that instance.
WebResponse resObj = reqObj.GetResponse();
The above code will call the url which we passed in the create() method in step 1.We are assigning the returned value of the GetResponse() method to WebResponse object.WebResponse is an abstract class.So a derived class object is used depending on the scenario such as FileWebResponse or HttpWebResponse.Here the derived class is HttpWebResponse.
Like the WebRequest class ,the WebResponse class includes many useful properties:
3.Finally close the WebResponse object to clean the system resources.
resObj .Close();
Leave a Reply