How to: Send Data Using the WebRequest Class
2008-01-29 21:18
525 查看
The following procedure describes the steps used to send data to a server. This procedure is commonly used to post data to a Web page.
C#
Copy Code
Visual Basic
Copy Code
Set any property values that you need in the WebRequest. For example, to enable authentication, set the Credentials property to an instance of the NetworkCredential class.
C#
Copy Code
Visual Basic
Copy Code
In most cases, the WebRequest instance itself is sufficient to send data. However, if you need to set protocol-specific properties, you must cast the WebRequest to the protocol-specific type. For example, to access the HTTP-specific properties of HttpWebRequest, cast the WebRequest to an HttpWebRequest reference. The following code example shows how to set the HTTP-specific UserAgent property.
C#
Copy Code
Visual Basic
Copy Code
Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method.
C#
Copy Code
Visual Basic
Copy Code
Set the ContentLength property.
C#
Copy Code
Visual Basic
Copy Code
Set the ContentType property to an appropriate value.
C#
Copy Code
Visual Basic
Copy Code
Get the stream that holds request data by calling the GetRequestStream method.
C#
Copy Code
Visual Basic
Copy Code
Write the data to the Stream object returned by this method.
C#
Copy Code
Visual Basic
Copy Code
Close the request stream by calling the Stream.Close method.
C#
Copy Code
Visual Basic
Copy Code
Send the request to the server by calling GetResponse. This method returns an object containing the server's response. The returned WebResponse object's type is determined by the scheme of the request's URI.
C#
Copy Code
Visual Basic
Copy Code
You can access the properties of the WebResponse or cast the WebResponse to a protocol-specific instance to read protocol-specific properties. For example, to access the HTTP-specific properties of HttpWebResponse, cast the WebResponse to an HttpWebResponse reference.
C#
Copy Code
Visual Basic
Copy Code
To get the stream containing response data sent by the server, call the GetResponseStream method of the WebResponse.
C#
Copy Code
Visual Basic
Copy Code
After reading the data from the response, you must either close the response stream using the Stream.Close method or close the response using the WebResponse.Close method. It is not necessary to call the Close method on both the response stream and the WebResponse, but doing so is not harmful.
C#
Copy Code
Visual Basic
Copy Code
Copy Code
Visual Basic
Copy Code
To send data to a host server
Create a WebRequest instance by calling Create with the URI of the resource that accepts data, for example, a script or ASP .NET page.C#
Copy Code
WebRequest request = WebRequest.Create("http://www.contoso.com/");
Visual Basic
Copy Code
Dim request as WebRequest = WebRequest.Create("http://www.contoso.com/")
Note |
---|
The .NET Framework provides protocol-specific classes derived from WebRequest and WebResponse for URIs that begin with "http:", "https:'', "ftp:", and "file:". To access resources using other protocols, you must implement protocol-specific classes that derive from WebRequest and WebResponse. For more information, see Programming Pluggable Protocols . |
C#
Copy Code
request.Credentials = CredentialCache.DefaultCredentials;
Visual Basic
Copy Code
request.Credentials = CredentialCache.DefaultCredentials
In most cases, the WebRequest instance itself is sufficient to send data. However, if you need to set protocol-specific properties, you must cast the WebRequest to the protocol-specific type. For example, to access the HTTP-specific properties of HttpWebRequest, cast the WebRequest to an HttpWebRequest reference. The following code example shows how to set the HTTP-specific UserAgent property.
C#
Copy Code
((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";
Visual Basic
Copy Code
Ctype(request,HttpWebRequest).UserAgent = ".NET Framework Example Client"
Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method.
C#
Copy Code
request.Method = "POST";
Visual Basic
Copy Code
request.Method = "POST"
Set the ContentLength property.
C#
Copy Code
request.ContentLength = byteArray.Length;
Visual Basic
Copy Code
request.ContentLength = byteArray.Length
Set the ContentType property to an appropriate value.
C#
Copy Code
request.ContentType = "application/x-www-form-urlencoded";
Visual Basic
Copy Code
request.ContentType = "application/x-www-form-urlencoded"
Get the stream that holds request data by calling the GetRequestStream method.
C#
Copy Code
Stream dataStream = request.GetRequestStream ();
Visual Basic
Copy Code
Stream dataStream = request.GetRequestStream ()
Write the data to the Stream object returned by this method.
C#
Copy Code
dataStream.Write (byteArray, 0, byteArray.Length);
Visual Basic
Copy Code
dataStream.Write (byteArray, 0, byteArray.Length)
Close the request stream by calling the Stream.Close method.
C#
Copy Code
dataStream.Close ();
Visual Basic
Copy Code
dataStream.Close ()
Send the request to the server by calling GetResponse. This method returns an object containing the server's response. The returned WebResponse object's type is determined by the scheme of the request's URI.
C#
Copy Code
WebResponse response = request.GetResponse();
Visual Basic
Copy Code
Dim response As WebResponse = request.GetResponse()
Note |
---|
After you are finished with a WebResponse object, you must close it by calling the Close method. Alternatively, if you have gotten the response stream from the response object, you can close the stream by calling the System.IO.Stream.Close method. If you do not close the response or the stream, your application can run out of connections to the server and become unable to process additional requests. |
C#
Copy Code
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
Visual Basic
Copy Code
Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
To get the stream containing response data sent by the server, call the GetResponseStream method of the WebResponse.
C#
Copy Code
Stream data = response.GetResponseStream;
Visual Basic
Copy Code
Dim data As Stream = response.GetResponseStream
After reading the data from the response, you must either close the response stream using the Stream.Close method or close the response using the WebResponse.Close method. It is not necessary to call the Close method on both the response stream and the WebResponse, but doing so is not harmful.
C#
Copy Code
response.Close();
Visual Basic
Copy Code
response.Close()
Example
C#Copy Code
using System; using System.IO; using System.Net; using System.Text; namespace Examples.System.Net { public class WebRequestPostExample { public static void Main () { // Create a request using a URL that can receive a post. WebRequest request = WebRequest.Create ("http://www.contoso.com/PostAccepter.aspx "); // Set the Method property of the request to POST. request.Method = "POST"; // Create POST data and convert it to a byte array. string postData = "This is a test that posts this string to a Web server."; byte[] byteArray = Encoding.UTF8.GetBytes (postData); // Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded"; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream (); // Write the data to the request stream. dataStream.Write (byteArray, 0, byteArray.Length); // Close the Stream object. dataStream.Close (); // Get the response. WebResponse response = request.GetResponse (); // Display the status. Console.WriteLine (((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. 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); // Clean up the streams. reader.Close (); dataStream.Close (); response.Close (); } } }
Visual Basic
Copy Code
Imports System Imports System.IO Imports System.Net Imports System.Text Namespace Examples.System.Net Public Class WebRequestPostExample Public Shared Sub Main() ' Create a request using a URL that can receive a post. Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ") ' Set the Method property of the request to POST. request.Method = "POST" ' Create POST data and convert it to a byte array. Dim postData As String = "This is a test that posts this string to a Web server." Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData) ' Set the ContentType property of the WebRequest. request.ContentType = "application/x-www-form-urlencoded" ' Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length ' Get the request stream. Dim dataStream As Stream = request.GetRequestStream() ' Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length) ' Close the Stream object. dataStream.Close() ' Get the response. Dim response As WebResponse = request.GetResponse() ' Display the status. Console.WriteLine(CType(response, HttpWebResponse).StatusDescription) ' Get the stream containing content returned by the server. dataStream = response.GetResponseStream() ' Open the stream using a StreamReader for easy access. Dim reader As New StreamReader(dataStream) ' Read the content. Dim responseFromServer As String = reader.ReadToEnd() ' Display the content. Console.WriteLine(responseFromServer) ' Clean up the streams. reader.Close() dataStream.Close() response.Close() End Sub End Class End Namespace
相关文章推荐
- How to: Send Data Using the WebRequest Class
- send a client certificate by using the HttpWebRequest and HttpWebResponse classes
- SendPostDataByWebRequest
- Using Timer to get history values from EDNA database, an error is prompted in the page : "Sys.WebForms.PageRequestManagerTimeout
- 2010年7月19日_周一_Using the Common Data Source API in a Web application
- How to: Send and Receive Large Amounts of Data to and from a Web Service
- Get data from specified URI using WebRequest and WebResponse(读取网页数据并存入对应html文档)
- Send Raw Data to a Printer by Using the Win32 API
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- Using the Android Application class to persist data
- Using RestTemplate, how to send the request to a proxy first so I can use my junits with JMeter?
- Using the HTMLControl Class in Adobe AIR to parse HTML as a data source
- using WebRequest to get resource in the internet
- Building a Robust Web Based Email Client (WebMail) Using the IP*Works! ADO.NET Data Provider(中文)
- Python Web-第四周-Programs that Surf the Web(Using Python to Access Web Data)
- Making raw web service calls with the HttpWebRequest class
- Building a Robust Web Based Email Client (WebMail) Using the IP*Works! ADO.NET Data Provider(原文)
- Using the Message Class---Data Transfer in Service Contracts
- [Project] Simulate HTTP Post Request to obtain data from Web Page by using Python Scrapy Framework
- Use C# to get JSON Data from the Web and Map it to .NET Class => Made Easy! 转