C# 在C中使用url#

C# 在C中使用url#,c#,python,.net,url,urlrequest,C#,Python,.net,Url,Urlrequest,这段代码是用python编写的: import urllib3 http = urllib3.PoolManager() url = "http://www.example.com/" req = http.request('GET', url) source = req.dat 我想知道如何用C#编写它。使用以下代码: using (WebClient client = new WebClient ()) // Use using, for automatic dispose of clie

这段代码是用python编写的:

import urllib3
http = urllib3.PoolManager()
url = "http://www.example.com/"
req = http.request('GET', url)
source = req.dat
我想知道如何用C#编写它。

使用以下代码:

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;

但是Oliver的回答提供了更多的控制:)。

看起来您正在下载一个web响应。下面是一种方法:

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();
}
但Max的答案更简单:)。

如果您只想从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);
  }

这段代码应该做什么?将url的html或xml源分配给字符串@maxmomersteeg可能是@BardiaHeydari的复制品你发现了吗?我喜欢!适合下载到
字符串
。如果它需要用户名和密码怎么办?然后使用:
if(Object.ReferenceEquals(null,WebRequest.DefaultWebProxy.Credentials))WebRequest.DefaultWebProxy.Credentials=CredentialCache.DefaultCredentials,代码由@Dmitry Bychenko编写,将提供默认凭据。