This is preliminary documentation and subject to change.
To comment on this topic, please send us email at ngwssdk@microsoft.com. Thanks!
Using Internet Request and Response Classes
The steps for requesting data from the Internet and reading the response are:
- If you are accessing a resource such as a Web page using HTTP, simply create a WebRequest by calling Create on the WebRequestFactory with the URI of the resource you want to use. If you are accessing a non-HTTP resource, first register the WebRequest descendent that will handle the protocol you want to use by calling Register on WebRequestFactory, and then calling Create. The following code will create a WebRequest instance for an HTTP resource:
WebRequest req = WebRequestFactory.Create("http://www.microsoft.com/")
- Set any property values that you need in the WebRequest instance. In most cases the WebRequest instance will be sufficient to send and receive data. In the event that you need to set protocol-specific properties, typecast the WebRequest instance to the protocol specific instance. For example, to access the HTTP-specific properties of HttpWebRequest, typecast the WebRequest to HttpWebRequest. The following code will set the UserAgent property:
HttpWebRequest(req).UserAgent="NGWS Frameworks Example Client";
- To download a resource from the Internet, call the GetResponse method of your WebRequest instance to make the request to the Internet resource and return the response. When sending or uploading data to a resource, call the GetRequestStream method of your WebRequest and use the resulting Stream object to write the data. When you've finished uploading, GetResponse can be called to ensure that the data was received correctly by the server. The actual class of the WebResponse instance returned is determined by the scheme of the requested URI.
WebResponse resp = req.GetResponse();
- Use the GetResponseStream method of the WebResponse instance to get the stream containing the response data. Reading the returned stream provides the data from the network resource. You can also access the properties of the WebResponse instance, or typecast the WebResponse instance to a protocol-specific instance to read protocol-specific properties. For example, to access the HTTP-specific properties of HttpWebResponse, typecast the WebResponse to HttpWebResponse. The following code illustrates accessing an HTTP-specific property and reading the response stream:
// Read an HTTP specific property:
DateTime Updated = HttpWebRequest(resp).LastModified;
// Get the response stream:
Stream resp = resp.GetResponseStream();
// Create a buffer to hold the response data:
int BufferSize = 512;
Byte[] Buffer = new Byte[BufferSize];
// Read the stream to access the data:
int BytesRead = respstrm.Read(Buffer, 0, BufferSize);
while (BytesRead != 0)
{
Console.Write(Encoding.ASCII.GetString(Buffer, 0, BytesRead));
BytesRead = respstrm.Read(Buffer, 0, BufferSize);
}