• How to: Send Data Using the WebRequest Class


    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.

    To send data to a host server

    1. Create a WebRequest instance by calling Create with the URI of the resource that accepts data, for example, a script or ASP .NET page.

      WebRequest request = WebRequest.Create("http://www.contoso.com/");
          
      Visual Basic
      Dim request as WebRequest = WebRequest.Create("http://www.contoso.com/")
          
      NoteNote

      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 .

    2. 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.

      request.Credentials = CredentialCache.DefaultCredentials;
          
      Visual Basic
      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.

      ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";
          
      Visual Basic
      Ctype(request,HttpWebRequest).UserAgent = ".NET Framework Example Client"
          
    3. Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method.

      request.Method = "POST";
          
      Visual Basic
      request.Method = "POST"
          
    4. Set the ContentLength property.

      request.ContentLength = byteArray.Length;
          
      Visual Basic
      request.ContentLength = byteArray.Length
          
    5. Set the ContentType property to an appropriate value.

      request.ContentType = "application/x-www-form-urlencoded";
          
      Visual Basic
      request.ContentType = "application/x-www-form-urlencoded"
          
    6. Get the stream that holds request data by calling the GetRequestStream method.

      Stream dataStream = request.GetRequestStream ();
          
      Visual Basic
      Stream dataStream = request.GetRequestStream ()
          
    7. Write the data to the Stream object returned by this method.

      dataStream.Write (byteArray, 0, byteArray.Length);
          
      Visual Basic
      dataStream.Write (byteArray, 0, byteArray.Length)
          
    8. Close the request stream by calling the Stream.Close method.

      dataStream.Close ();
          
      Visual Basic
      dataStream.Close ()
          
    9. 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.

      WebResponse response = request.GetResponse();
          
      Visual Basic
      Dim response As WebResponse = request.GetResponse()
          
      NoteNote

      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.

    10. 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.

      Console.WriteLine (((HttpWebResponse)response).StatusDescription);
          
      Visual Basic
      Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)
          
    11. To get the stream containing response data sent by the server, call the GetResponseStream method of the WebResponse.

      Stream data = response.GetResponseStream;
          
      Visual Basic
      Dim data As Stream = response.GetResponseStream
          
    12. 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.

      response.Close();
          
      Visual Basic
      response.Close()
          

    Example

    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
    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
    
  • 相关阅读:
    Enable SPI 1.0 and 1.1 with device tre overlays on BeagleBone
    [转]使用Beaglebone Black的SPI
    真相:中国版BBB用USB连电脑没有盘符的根本原因分析
    Linux下使用locale命令设置语言环境
    locale 详解
    locale的设定及其LANG、LC_ALL、LANGUAGE环境变量的区别
    嵌入式Qt4.7.1安装详解
    【转】补充说明:关于Beaglebone black上debian无图形界面的问题及QT的窗口示例
    【转】BeagleBone Black USB一线通(3)
    [转]BeagleBone Black USB一线通(2)
  • 原文地址:https://www.cnblogs.com/goody9807/p/960009.html
Copyright © 2020-2023  润新知