-1

这段代码是用python编写的:

import urllib3
http = urllib3.PoolManager()
url = "http://www.example.com/"
req = http.request('GET', url)
source = req.dat

我想知道如何用 C# 编写它。

4

3 回答 3

3

使用以下代码:

using (WebClient client = new WebClient ()) // Use using, for automatic dispose of client
{
    //Get HTMLcode from page
    string htmlCode = client.DownloadString("http://www.example.com");
}

System.Net在您的班级顶部添加参考:

using System.Net;

但是奥利弗的回答提供了更多的控制权:)。

于 2014-02-06T10:49:43.677 回答
2

您似乎正在下载网络响应。以下是执行此操作的一种方法:

var request = (HttpWebRequest)WebRequest.Create("http://www.example.com/");

using (var stream = request.GetResponse().GetResponseStream())
{
   var reader = new StreamReader(stream, Encoding.UTF8);
   var responseString = reader.ReadToEnd();
}

但马克斯的回答更容易:)。

于 2014-02-06T10:49:56.413 回答
2

如果您只想从 URL 下载,可以尝试使用

  String url = @"http://www.example.com/";
  Byte[] dat = null;

  // In case you need credentials for Proxy
  if (Object.ReferenceEquals(null, WebRequest.DefaultWebProxy.Credentials))
    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;

  using (WebClient wc = new WebClient()) {
    // Seems that you need raw data, Byte[]; if you want String - wc.DownLoadString(url);
    dat = wc.DownloadData(url);
  }
于 2014-02-06T10:54:47.470 回答