您的位置:首页 > 产品设计 > UI/UE

C#:使用WebRequest类请求数据

2016-01-25 09:37 429 查看
本文翻译于:https://msdn.microsoft.com/en-us/library/456dfw4f(v=vs.110).aspx

下列程序描述的步骤用于从服务器请求一个资源,例如,一个Web页面或文件。必须由URI标识的资源。

从主机服务器请求数据:

1、创建一个WebRequest实例通过调用创建URI的资源。

  WebRequest request = WebRequest.Create("http://www.contoso.com/");

note:

  .net 框架提供了特定于协议的类来自WebRequest和WebResponse uri以“http:”开始,“https:“,“ftp:”,“文件:”。使用其他协议来访问资源,您必须实现特定于协议的类来自WebRequest WebResponse。有关更多信息,请参见编程可插协议。

2、设置在WebRequest任何你需要的属性值。例如,要启用身份验证,设置凭证属性NetworkCredential类的一个实例。

  request.Credentials = CredentialCache.DefaultCredentials;

  在大多数情况下,WebRequest类足以接收数据。然而,如果你需要设置特定于协议的特性,你必须把WebRequest特定于协议的类型。例如,访问HTTP-specific HttpWebRequest的性质,把WebRequest HttpWebRequest参考。以下代码示例展示了如何设置HTTP-specific UserAgent属性。

  ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";

3、向服务器发送请求,调用GetResponse。返回的WebResponse对象的实际类型是由请求的URI的方案。

  WebResponse response = request.GetResponse();

  你完成了一个WebResponse对象后,您必须关闭它通过调用方法。或者,如果您得到的响应流响应对象,您可以关闭流通过调用流。关闭方法。如果你不关闭响应或流,您的应用程序可以运行的连接到服务器并成为无法处理其他请求。

4、您可以访问的属性WebResponse或铸WebResponse读特定于协议的特定于协议的实例属性。例如,访问HTTP-specific HttpWebResponse的性质,把WebResponse HttpWebResponse参考。以下代码示例展示了如何显示状态信息发送响应。

  Console.WriteLine (((HttpWebResponse)response).StatusDescription);

5、得到包含响应由服务器发送的数据流,使用GetResponseStream WebResponse的方法。

  Stream dataStream = response.GetResponseStream ();

6、阅读响应的数据之后,您必须使用流关闭响应流。关闭方法或关闭使用WebResponse响应。关闭方法。没有必要调用关闭方法在响应流和WebResponse,但这样做并不是有害的。WebResponse。比分接近的流。关闭时关闭响应。

  response.Close();

Demo:


using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
public class WebRequestGetExample
{
public static void Main ()
{
// Create a request for the URL.
WebRequest request = WebRequest.Create (
"http://www.contoso.com/default.html");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream 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 and the response.
reader.Close ();
response.Close ();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: