这段代码是用python编写的:
import urllib3
http = urllib3.PoolManager()
url = "http://www.example.com/"
req = http.request('GET', url)
source = req.dat
我想知道如何用 C# 编写它。
这段代码是用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;
但是奥利弗的回答提供了更多的控制权:)。
您似乎正在下载网络响应。以下是执行此操作的一种方法:
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();
}
但马克斯的回答更容易:)。
如果您只想从 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);
}