http请求与响应的实例代码详解

发布时间:2020-11-02编辑:脚本学堂
本文介绍下,有关http请求与响应的一些实例代码,分为c#与vb.net两个版本,有需要的朋友,参考下吧。

若要从 Internet 请求数据并读取响应,请完成以下步骤
如果要访问像 Web 页这样的资源,请用要使用的资源的 URI 调用 WebRequest.Create 来创建 WebRequest,如下例所示。
 

复制代码 代码示例:
[C#]
WebRequest wReq = WebRequest.Create("http://www.jb200.com/");
[Visual Basic]
Dim wReq as WebRequest = WebRequest.Create("http://www.jb200.com/")
 

注意   .NET Framework 为以“http:”、“https:”和“file:”开头的 URI 提供特定于协议的 WebRequest 和 WebResponse 子代。若要访问其他协议,必须实现协议特定的 WebRequest 和 WebResponse 子代。有关更多信息,请参见编写可插接协议。
在 WebRequest 中设置任何所需的属性值。例如,若要支持身份验证,请将 Credentials 属性设置为 NetworkCredential 类的实例,如下例所示。
 

复制代码 代码示例:
[C#]
wReq.Credentials =
   new NetworkCredential(UserName, SecurelyStoredPassword);
[Visual Basic]
wReq.Credentials = _
   New NetworkCredential(UserName, SecurelyStoredPassword)
 

大多数情况下,WebRequest 本身就已足够发送和接收数据。但是,如果需要设置特定于协议的属性,则应将 WebRequest 转换为特定于协议的实例。仅当处理 WebRequest 的 WebRequest 子代正确时,此类型转换才有效。例如,若要访问 HttpWebRequest 的 HTTP 特定的属性,请将 WebRequest 转换为 HttpWebRequest。下面的代码实例显示如何设置 HTTP 特定的 UserAgent 属性。
 

复制代码 代码示例:
[C#]
if (wReq is HttpWebRequest)
{
   ((HttpWebRequest)wReq).UserAgent = ".NET Framework Example Client";
}
[Visual Basic]
If TypeOf wReq is HttpWebRequest Then
   Ctype(wReq,HttpWebRequest).UserAgent = _
      ".NET Framework Example Client"
End If
 

若要从 Internet 下载资源,请调用 WebRequest 的 GetResponse 方法。
若要将数据发送或上载到资源,请调用 WebRequest 的 GetRequestStream 方法,并使用结果 Stream 对象编写数据。完成上载后,必须使用 Stream.Close 方法关闭请求流。关闭流后,可以调用 GetResponse 以确保服务器已正确接收到数据。为 WebResponse 实例返回的实际类由所请求的 URI 方案决定。下面的代码示例显示如何使用 GetResponse 方法创建 WebResponse。
 

复制代码 代码示例:
[C#]
WebResponse wResp = wReq.GetResponse();
[Visual Basic]
Dim wResp As WebResponse = wReq.GetResponse()
 

注意   调用 WebResponse 后,必须使用 WebResponse.Close 或 Stream.Close 关闭响应。如果不关闭每个响应,应用程序将用完与服务器的连接,而无法处理其他请求。
使用 WebResponse 的 GetResponseStream 方法从网络资源中获取包含响应数据的流。还可以访问 WebResponse 的属性或将 WebResponse 转换为特定于协议的实例以读取特定于协议的属性。例如,若要访问 HttpWebResponse 的 HTTP 特定的属性,请将 WebResponse 转换为 HttpWebResponse。下面的代码示例显示如何访问 HTTP 特定的属性和读取响应流。
 

复制代码 代码示例:

[C#]
// Read an HTTP-specific property.
if (wResp is HttpWebResponse)
{
   DateTime Updated = ((HttpWebResponse)wResp).LastModified;
}
// Get the response stream.
Stream respStream = wResp.GetResponseStream();

// This example uses a StreamReader to read the entire response
// into a string and then writes the string to the console.
StreamReader reader = new StreamReader(respStream, Encoding.ASCII);
String respHTML = reader.ReadToEnd();
Console.WriteLine(respHTML);

// Close the response stream.
respStream.Close();
[Visual Basic]
' Read an HTTP-specific property.
If TypeOf wResp Is HttpWebResponse Then
  Dim updated As DateTime = Ctype(wResp,HttpWebResponse).LastModified
End If

' Get the response stream.
Dim respStream As Stream = wResp.GetResponseStream()

' This example uses a StreamReader to read the entire response
' into a string and then writes the string to the console.
Dim reader As StreamReader = _
   New StreamReader(respStream, Encoding.ASCII)
Dim respHTML as String = reader.ReadToEnd()
Console.WriteLine(respHTML)

' Close the response stream
respStream.Close()
 

如果应用程序只需要 WebResponse 中返回的标头信息并忽略任何返回的数据,则不必获取响应流。下面的代码示例显示如何从 Internet 主机返回服务器标头信息。
 

复制代码 代码示例:
[C#]
WebRequest wReq = WebRequest.Create("http://www.jb200.com");
WebResponse wResp = wReq.GetResponse();
string server = wResp.Headers["Server"];
[Visual Basic]
Dim wReq As WebRequest = WebRequest.Create("http://www.jb200.com")
Dim wResp As WebResponse = wReq.GetResponse()
Dim server As String = wResp.Headers("Server")
 

读取响应中的数据后,必须使用 Stream.Close 方法关闭所有打开的流或使用 WebResponse.Close 方法关闭响应。
 

复制代码 代码示例:
[C#]
wResp.Close();
[Visual Basic]
wResp.Close()
 

不必在响应流和 WebResponse 上都调用 Close 方法,但这样做并没有什么害处。WebResponse.Close 在关闭响应时调用 Stream.Close。
以下示例应用程序说明如何使用 WebRequest 和 WebResponse 类。
 

复制代码 代码示例:

[C#]
using System;
using System.Net;
using System.Text;
using System.IO;

class ClientGet {
   public static void Main(string[] args)
   {
      if (args.Length < 1)
      {
        showusage();
        return;
      }

      // Get the URI from the command line.
      Uri site = new Uri(args[0]);

      // Create the request instance.
      WebRequest wReq = WebRequest.Create(site);

      // Set the HTTP-specific UserAgent property
      if (wReq is HttpWebRequest)
      {
        ((HttpWebRequest)wReq).UserAgent =
          ".NET Framework Example Client";
      }

      // Get the response instance
      WebResponse wResp = wReq.GetResponse();

      // Read an HTTP-specific property.
      if (wResp is HttpWebResponse)
      {
        DateTime updated = ((HttpWebResponse)wResp).LastModified;
      }

      // Get the response stream.
      Stream respStream = wResp.GetResponseStream();

     // This example uses a StreamReader to read the entire response
     // into a string and then writes the string to the console.
     StreamReader reader =
       new StreamReader(respStream, Encoding.ASCII);
     String respHTML = reader.ReadToEnd();
     Console.WriteLine(respHTML);

     // Close the response and response stream.
     wResp.Close();
   }
   public static void showusage()
   {
      Console.WriteLine("Attempts to GET a URI.");
      Console.WriteLine("rnUsage:");
      Console.WriteLine("  ClientGet URI");
      Console.WriteLine("Example:");
      Console.WriteLine("  ClientGet http://www.jb200.com/");
   }
}
[Visual Basic]
Imports System
Imports System.Net
Imports System.IO
Imports System.Text
Imports Microsoft.VisualBasic

Class ClientGet
Public Shared Sub Main()
  Dim Args() As String = System.Environment.GetCommandLineArgs()
  If Args.Length < 2 Then
    ShowUsage
    Return
  End If

  ' Get the URI from the command line.
  Dim site As Uri = New Uri(Args(1))

  ' Create the request instance.
  Dim wReq as WebRequest = WebRequest.Create(site)

  ' Set the HTTP-specific UserAgent property.
  If TypeOf wReq Is HttpWebRequest Then
     CType(wReq, HttpWebRequest).UserAgent = _
       ".NET Framework Example Client"
  End If

  ' Get the response instance.
  Dim wResp As WebResponse = wReq.GetResponse()

  ' Read an HTTP-specific property
  If TypeOf wResp is HttpWebResponse Then
    Dim updated As DateTime = CType(wResp,HttpWebResponse).LastModified
  End If

  ' Get the response stream.
  Dim respStream As Stream = wResp.GetResponseStream()

  ' Use the Stream. This example reads the entire response with a
  ' StreamReader into a string, and then writes the string to the
  ' console.
  Dim reader As StreamReader = _
    New StreamReader(respStream, Encoding.ASCII)
  Dim respHTML As String = reader.ReadToEnd()
  Console.WriteLine(respHTML)

  ' Close the response and response stream.
  wResp.Close()
End Sub

Public Shared Sub ShowUsage
  Console.WriteLine("Attempts to GET a URI")
  Console.WriteLine(Constants.vbCrLf & "Usage")
  Console.WriteLine("  ClientGet URI")
  Console.WriteLine("Example")
  Console.WriteLIne("  ClientGet http://www.jb200.com")
End Sub
End Class