Bogotobogo
contact@bogotobogo.com
- .NET Framework
- Introduction - My First C# Code
- System Members and Data
- Modifiers
- Array
- Enumeration (Enums)
- Value and Reference Types
- Constructor and this Keyword
- static Keyword
- Encapsulation Services
- Inheritance
- Inheritance II
- Polymorphism
- Interfaces
- Delegates
- System.Object
- Events
- Multi Threading I - Introduction and Simple Thread
- Multi Threading II - ThreadStart/ParameterizedThreadStart, Foreground/Background Threads
- Multi Threading III - Concurrency, Synchronization
- Networking I - PORT, IPv4/IPv6, TCP/UDP, URI
- Networking II - WebRequest/WebResponse, WebClient
- Networking II - WebRequest/WebResponse, WebClient
When a client machine launches a web browser, an HTTP request is made to access a particular resource which is usually a web page on the remote server machine. For example, if we navigate to http://www.bogotobogo.com, the browser uses Domain Name Service (DNS) that converts the registered URL into a 32-bit value (IP address). At this point, the browser opens a socket connection (port 80 for nonsecure connection) and sends the HTTP request for processing to the target site.
The web server receives the incoming HTTP request and process any client supplied input values in order to format a proper HTTP response. Web developer may use any technologies (CGI, ASP, ASP.NET, JSP, etc.) to dynamically generate the content to be emitted into the HTTP response. At this point, the client-side browser renders the HTML sent from the web server.
HTTP is a stateless protocol. In other words, as soon as the web server emits a response to the client, everything about the previous interaction is forgotten. This is clearly not the case for desktop applications, where the state of the executable is most often alive and running until the user shuts down the application.
So, it is up to us take specific steps to remember information about the users who are currently logged on to our site.
A web application is a collection of files such as *.html, *.asp, image files, XML data, and so on. It also consists of related components such as a .NET code library stored within a set of directories on a given web server. Web applications have a specific life cycle and have numerous events that we can hook into.
A web server is software which is in charge of hosting our web applications. It typically provides a number of related services such as security, FTP, mail exchange services, and so forth. Internet Information Services (IIS) is Microsoft's enterprise level web server. IIS has intrinsic support for classic ASP and ASP.NET web applications.
WebRequest and WebResponse are the common base classes for managing both HTTP and FTP client-side activity as well as the file: protocol. They encapsulate the request/response model that these protocols all share: the client makes a request, and then awaits a response from a server.
WebClient is a façade class calling WebRequest and WebResponse. WebClient gives us a choice of dealing in strings, arrays, streams, and files. WebRequest and WebResponse support just streams. However, we cannot rely entirely on WebClient because some feature such as cookies are available only through WebRequest and WebResponse.
Constructor
| WebClient | Initializes a new instance of the WebClient class. |
Properties
| BaseAddress | Gets or sets the base URI for requests made by a WebClient. |
| CachePolicy | Gets or sets the application's cache policy for any resources obtained by this WebClient instance using |
| CanRaiseEvents | Gets a value indicating whether the component can raise an event. (Inherited from Component). |
| Container | Gets the IContainer that contains the Component. (Inherited from Component). |
| Credentials | Gets or sets the network credentials that are sent to the host and used to authenticate the request. |
| DesignMode | Gets the Gets a value that indicates whether the Component is currently in design mode. (Inherited from Component). |
| Encoding | Gets and sets the Encoding used to upload and download strings. |
| Events | Gets the list of event handlers that are attached to this Component. (Inherited from Component). |
| Headers | Gets or sets a collection of header name/value pairs associated with the request. |
| IsBusy | Gets whether a Web request is in progress. |
| Proxy | Gets or sets the proxy used by this WebClient object. |
| QueryString | Gets or sets a collection of query name/value pairs associated with the request. |
| ResponseHeaders | Gets a collection of header name/value pairs associated with the response. |
| Site | Gets or sets the ISite of the Component. (Inherited from Component). |
| UseDefaultCredentials | Gets or sets a Boolean value that controls whether the DefaultCredentials are sent with requests. |
Download Methods
| DownloadData(String) | Downloads the resource with the specified URI as a Byte array. |
| DownloadData(Uri) | Downloads the resource with the specified URI as a Byte array. |
| DownloadDataAsync(Uri) | Downloads the specified resource as a Byte array. This method does not block the calling thread. |
| DownloadDataAsync(Uri, Object) | Downloads the specified resource as a Byte array. This method does not block the calling thread. |
| DownloadFile(String, String) | Downloads the resource with the specified URI to a local file. |
| DownloadFile(Uri, String) | Downloads the resource with the specified URI to a local file. |
| DownloadFileAsync(Uri, String) | Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread. |
| DownloadFileAsync(Uri, String, Object) | Downloads, to a local file, the resource with the specified URI. This method does not block the calling thread. |
| DownloadString(String) | Downloads the requested resource as a String. The resource to download is specified as a Uri. |
| DownloadStringAsync(Uri) | Downloads the resource specified as a Uri. This method does not block the calling thread. |
| OpenRead(String) | Opens a readable stream for the data downloaded from a resource with the URI specified as a String. |
| OpenRead(Uri) | Opens a readable stream for the data downloaded from a resource with the URI specified as a Uri |
| OpenReadAsync(Uri) | Opens a readable stream containing the specified resource. This method does not block the calling thread. |
| OpenReadAsync(Uri, Object) | Opens a readable stream containing the specified resource. This method does not block the calling thread. |
Upload Methods
| UploadData(String, Byte[]) | Uploads a data buffer to a resource identified by a URI. |
| UploadData(Uri, Byte[]) | Uploads a data buffer to a resource identified by a URI. |
| UploadData(String, String, Byte[]) | Uploads a data buffer to the specified resource, using the specified method. |
| UploadData(Uri, String, Byte[]) | Uploads a data buffer to the specified resource, using the specified method. |
| UploadDataAsync(Uri, Byte[]) | Uploads a data buffer to a resource identified by a URI, using the POST method. This method does not block the calling thread. |
| UploadDataAsync(Uri, String, Byte[]) | Uploads a data buffer to a resource identified by a URI, using the specified method. This method does not block the calling thread. |
| UploadDataAsync(Uri, String, Byte[], Object) | Uploads a data buffer to a resource identified by a URI, using the specified method and identifying token. |
| UploadFile(String, String) | Uploads the specified local file to a resource with the specified URI. |
| UploadFile(Uri, String) | Uploads the specified local file to a resource with the specified URI. |
| UploadFile(String, String, String) | Uploads the specified local file to the specified resource, using the specified method. |
| UploadFile(Uri, String, String) | Uploads the specified local file to the specified resource, using the specified method. |
| UploadFileAsync(Uri, String) | Uploads the specified local file to the specified resource, using the POST method. This method does not block the calling thread. |
| UploadFileAsync(Uri, String, String) | Uploads the specified local file to the specified resource, using the POST method. This method does not block the calling thread. |
| UploadFileAsync(Uri, String, String, Object) | Uploads the specified local file to the specified resource, using the POST method. This method does not block the calling thread. |
| UploadString(String, String) | Uploads the specified string to the specified resource, using the POST method. |
| UploadString(Uri, String) | Uploads the specified string to the specified resource, using the POST method. |
| UploadString(String, String, String) | Uploads the specified string to the specified resource, using the specified method. |
| UploadString(Uri, String, String) | Uploads the specified string to the specified resource, using the specified method. |
| UploadStringAsync(Uri, String) | Uploads the specified string to the specified resource. This method does not block the calling thread. |
| UploadStringAsync(Uri, String, String) | Uploads the specified string to the specified resource. This method does not block the calling thread. |
| UploadStringAsync(Uri, String, String, Object) | Uploads the specified string to the specified resource. This method does not block the calling thread. |
| UploadValues(String, NameValueCollection) | Uploads the specified name/value collection to the resource identified by the specified URI. |
| UploadValues(Uri, NameValueCollection) | Uploads the specified name/value collection to the resource identified by the specified URI. |
| UploadValues(String, String, NameValueCollection) | Uploads the specified name/value collection to the resource identified by the specified URI, using the specified method. |
| UploadValues(Uri, String, NameValueCollection) | Uploads the specified name/value collection to the resource identified by the specified URI, using the specified method. |
| UploadValuesAsync(Uri, NameValueCollection) | Uploads the data in the specified name/value collection to the resource identified by the specified URI. This method does not block the calling thread. |
| UploadValuesAsync(Uri, String, NameValueCollection) | Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the specified method. This method does not block the calling thread. |
| UploadValuesAsync(Uri, String, NameValueCollection, Object) | Uploads the data in the specified name/value collection to the resource identified by the specified URI, using the specified method. This method does not block the calling thread, and allows the caller to pass an object to the method that is invoked when the operation completes. |
| OpenWrite(String) | Opens a stream for writing data to the specified resource. |
| OpenWrite(Uri) | Opens a stream for writing data to the specified resource. |
| OpenWrite(String, String) | Opens a stream for writing data to the specified resource, using the specified method. |
| OpenWrite(Uri, String) | Opens a stream for writing data to the specified resource, by using the specified method. |
| OpenWriteAsync(Uri) | Opens a stream for writing data to the specified resource. This method does not block the calling thread. |
| OpenWriteAsync(Uri, String) | Opens a stream for writing data to the specified resource. This method does not block the calling thread. |
| OpenWriteAsync(Uri, String, Object) | Opens a stream for writing data to the specified resource, using the specified method. This method does not block the calling thread. |
The UploadValues methods can be used to post values to an HTTP form, with a method argument of POST. WebClient also has a BaseAddress property. This property allows us to specify a string to be prefixed to all addresses such as http://www.bogotobogo.com/Sitemap.xml/.
Let's run the following code as an example:
using System;
using System.Net;
using System.IO;
public class Test
{
public static void Main(string[] args)
{
if (args == null || args.Length == 0)
{
throw new ApplicationException("Specify the URI of the resource to retrieve.");
}
WebClient client = new WebClient();
// Add a user agent header in case the
// requested URI contains a query.
client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
Stream data = client.OpenRead(args[0]);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
Console.WriteLine(s);
data.Close();
reader.Close();
}
}
The argument for the code is shown in the picture below:
The output is the content of the "http://www.bogotobogo.com/index.html"
WebRequest and WebResponse are more complex to use than WebClient, but also more flexible.
WebRequest is the abstract base class for the .NET Framework's request/response model for accessing data from the Internet. An application that uses the request/response model can request data from the Internet in a protocol-agnostic manner, in which the application works with instances of the WebRequest class while protocol-specific descendant classes carry out the details of the request.
Requests are sent from an application to a particular URI, such as a Web page on a server. The URI determines the proper descendant class to create from a list of WebRequest descendants registered for the application. WebRequest descendants are typically registered to handle a specific protocol, such as HTTP or FTP, but can be registered to handle a request to a specific server or path on a server.
The WebRequest class throws a WebException when errors occur while accessing an Internet resource. The Status property is one of the WebExceptionStatus values that indicate the source of the error. When Status is WebExceptionStatus.ProtocolError, the Response property contains the WebResponse received from the Internet resource. Because the WebRequest class is an abstract class, the actual behavior of WebRequest instances at run time is determined by the descendant class returned by Create() method.
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main()
{
// Create a request for the URL.
WebRequest request
= WebRequest.Create("http://www.bogotobogo.com/index.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Display the status.
Console.WriteLine(response.StatusDescription);
// 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 responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Cleanup the streams and the response.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
- .NET Framework
- Introduction - My First C# Code
- System Members and Data
- Modifiers
- Array
- Enumeration (Enums)
- Value and Reference Types
- Constructor and this Keyword
- static Keyword
- Encapsulation Services
- Inheritance
- Inheritance II
- Polymorphism
- Interfaces
- Delegates
- System.Object
- Events
- Multi Threading I - Introduction and Simple Thread
- Multi Threading II - ThreadStart/ParameterizedThreadStart, Foreground/Background Threads
- Multi Threading III - Concurrency, Synchronization
- Networking I - PORT, IPv4/IPv6, TCP/UDP, URI
- Networking II - WebRequest/WebResponse, WebClient
- Networking II - WebRequest/WebResponse, WebClient