Its a bit of discussion as to use what ,when and how.
WebRequest request = WebRequest.Create(http://localhost/demosite);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string webResponseStream= reader.ReadToEnd();
reader.Close();
One can initiate request related to GET, POST, PUT method using httpClient.
Example:http://www.dotnetperls.com/httpclient
static async void DownloadPageAsync()
{
// ... Target page. string page = "http://en.wikipedia.org/"; // ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
Console.WriteLine(result.Substring(0, 50) + "...");
}
Comparison
http://blogs.k10world.com/technology/webclient-httpclient-consume-http-requests/
WebClient- Old .net framework
Most recently I used webrequest and Webresponse to read content of web pages like this.using System.Net.Web
WebRequest request = WebRequest.Create(http://localhost/demosite);
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string webResponseStream= reader.ReadToEnd();
reader.Close();
HttpClient: .net 4.5 more aligned to http web api.
using System.Net.Http;
Msdn : Provides a base class for sending HTTP requests and receiving HTTP responses from a resource identified by a URI.
Example:http://www.dotnetperls.com/httpclient
static async void DownloadPageAsync()
{
// ... Target page. string page = "http://en.wikipedia.org/"; // ... Use HttpClient.
using (HttpClient client = new HttpClient())
using (HttpResponseMessage response = await client.GetAsync(page))
using (HttpContent content = response.Content)
{
// ... Read the string.
string result = await content.ReadAsStringAsync();
// ... Display the result.
if (result != null &&
result.Length >= 50)
{
Console.WriteLine(result.Substring(0, 50) + "...");
}
Comparison
http://blogs.k10world.com/technology/webclient-httpclient-consume-http-requests/
No comments :
Post a Comment