Lect16 - HTTP II
Lect16 - HTTP II
Objectives:
Learn about classes in C# that simplify the creation of HTTP Clients
Learn how to pass a HTTP request through a proxy server
Learn how to write a simple Http Server
We saw in lecture 15, how to use the TcpClient class to create a HTTP
client.
Properties
Credentials Gets or sets the network credentials used to authenticate
the request with the Internet resource.
Headers Gets or sets a collection of header name/value pairs
associated with the request.
ResponseHeaders Gets a collection of header name/value pairs associated
with the response.
Methods
byte[] DownloadData(string uri); Downloads data from a resource
with the specified URI.
void DownloadFile(string uri, string Downloads data from a resource
fileName); with the specified URI to a local
file.
Stream OpenRead(string uri); Opens a readable stream for
the data downloaded from a
resource with the specified URI.
Stream OpenWrite(string uri); Opens a stream for writing data
Stream OpenWrite(string uri, string to a resource with the specified
method); URI.
byte[] UploadData(string uri, byte[] data); Uploads a data buffer to a
byte[] UploadData(string uri, string resource with the specified URI.
method, byte[] data);
void ShowHeaders() {
WebHeaderCollection whc = client.ResponseHeaders;
headerBox.Text = "";
for(int i=0; i<whc.Count; i++) {
headerBox.Text += whc.GetKey(i) + " : " + whc.Get(i) + "\r\n";
}
}
2. The NetworkCredential class
NetworkCredential();
NetworkCredential(string userName, string password);
NetworkCredential(string userName, string password, string domain);
Properties
Accept Gets or sets the value of the Accept HTTP header.
Address Gets the URI of the Internet resource that actually
responds to the request.
AllowAutoRedirect Gets or sets a value that indicates whether the
request should follow redirection responses.
ClientCertificates Gets the collection of security certificates associated
with this request.
Connection Gets or sets the value of the Connection HTTP
header.
ContentLength Gets or sets the Content-length HTTP header.
ContentType Overridden. Gets or sets the value of the Content-
type HTTP header.
Credentials Overridden. Provides authentication information for
the request.
HaveResponse Gets a value indicating whether a response has been
received from an Internet resource.
Headers Gets a collection of the name/value pairs that make
up the HTTP headers.
IfModifiedSince Gets or sets the value of the If-Modified-Since HTTP
header.
KeepAlive Gets or sets a value indicating whether to make a
persistent connection to the Internet resource.
MediaType Gets or sets the media type of the request.
Method Gets or sets the method for the request.
Pipelined Gets or sets a value indicating whether to pipeline the
request to the Internet resource.
ProtocolVersion Gets or sets the version of HTTP to use for the
request.
Proxy Gets or sets proxy information for the request.
SendChunked Gets or sets a value indicating whether to send data in
segments to the Internet resource.
UserAgent Gets or sets the value of the User-agent HTTP
header.
Methods
Abort Cancels a request to an Internet resource.
BeginGetRequestStream Begins an asynchronous request for a Stream
instance to use to write data.
BeginGetResponse Begins an asynchronous request to an Internet
resource.
EndGetRequestStream Ends an asynchronous request for a Stream
instance to use to write data.
EndGetResponse Ends an asynchronous request to an Internet
resource.
GetRequestStream Gets a Stream instance to use to write request
data.
GetResponse Returns a response from an Internet resource.
Example:
The following example shows a HTTP client, which can be used to
communicate with servers even beyond the local network.
void OnGetUrlClicked(object sender, System.EventArgs e)
{
headerBox.Text = "";
resultBox.Text = "";
NetworkCredential myCred = null;
WebProxy proxyObject = null;
if ( proxyPasswordBox.Text != "")
{
myCred = new NetworkCredential(proxyUsernameBox.Text,
proxyPasswordBox.Text, proxyDomainBox.Text);
proxyObject= new
WebProxy(proxyServerBox.Text+":"+proxyPortBox.Text,
true,null,
myCred);
//GlobalProxySelection.Select = proxyObject;
}
if (!hasProtocol(urlBox.Text))
urlBox.Text = "http://"+ urlBox.Text;
WebHeaderCollection whc;
WebResponse result = null;
try {
WebRequest req = WebRequest.Create(urlBox.Text);
if (proxyObject != null)
req.Proxy = proxyObject;
result = req.GetResponse();
Stream rs = result.GetResponseStream();
StreamReader sr = new StreamReader(rs);
resultBox.Text=sr.ReadToEnd();
whc = result.Headers;
for (int i=0; i<whc.Count; i++) {
headerBox.Text += whc.GetKey(i) + " : " + whc.Get(i) + "\r\
n";
}
result.Close();
}
catch(Exception) {
resultBox.Text = "Exception has occured";
}
}
Like any TCP server, a http server is created using the TcpListener
class or using the Socket class.
The following example shows a simple Http 1.0 server that supports
only the GET method.
using System;
using System.Collections;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
class SimpleHttpServer {
static int count = 0;
while (true)
{
TcpClient client = tcpListener.AcceptTcpClient();
Console.WriteLine("Visitor Count: "+ (++count));
ConnectionHandler handler = new ConnectionHandler(client);
ThreadPool.QueueUserWorkItem(new
WaitCallback(handler.HandleConnection), docFolder);
}
}
}
class ConnectionHandler
{
TcpClient client;
NetworkStream stream;
StreamReader reader;
StreamWriter writer;
string docFolder;
string request;
string input;
//read rest of the request
while ((input = reader.ReadLine()).Length != 0);
string[] token = request.Split(' ');
if (token.Length == 3 && token[0] == "GET" &&
token[1].StartsWith("/") && token[2].StartsWith("HTTP")) {