|
C# HTTP Protocol Program Example
Create a new console application project. You can use the project and solution names as shown in the following Figure.
Add the following code. |
using System; using System.IO; using System.Net; using System.Text;
namespace HttpChap6CS { /// <summary> /// Demonstrates the use of HttpWebRequest by /// downloading the contents of a URL and displaying /// them on the console. /// </summary> class Program { [STAThread] static void Main(string[] args) { try { // Create the request object, change the URI if you want HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.cuil.com/");
// Optionally, you can set HTTP-specific elements on the request, such as the User-Agent header request.UserAgent = "Test Client version 1.0";
// Issue the request HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Console.WriteLine("GetResponse() is OK...");
// Read the content StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.ASCII); string content = reader.ReadToEnd(); Console.WriteLine("ReadToEnd() is OK...");
// Display the content to the console Console.WriteLine(content); Console.WriteLine("WriteLine() is OK...");
Dim request As HttpWebRequest = WebRequest.Create("http://www.cuil.com/info/")
' Optionally, you can set HTTP-specific elements on the request, such as the User-Agent header request.UserAgent = "Test Client version 1.0"
' Issue the request Dim response As HttpWebResponse = request.GetResponse() Console.WriteLine("GetResponse() is OK...")
' Read the content Dim reader As New StreamReader(response.GetResponseStream(), Encoding.ASCII) Dim content As String = reader.ReadToEnd() Console.WriteLine("ReadToEnd() is OK...")
' Display the content to the console Console.WriteLine(content) Console.WriteLine("WriteLine() is OK...")
' Close the response response.Close() Console.WriteLine("Close() is OK...")
Catch wex As WebException Console.WriteLine(wex.ToString()) ' Check the status to see if there might be a response object If wex.Status = WebExceptionStatus.ProtocolError Then Dim response As HttpWebResponse = wex.Response Console.WriteLine() Console.WriteLine("The protocol error returned was '" & response.StatusCode.ToString & "'.") response.Close() End If End Try End Sub End Module |
Build and run the project (Start Without Debugging). The following is a sample output.