ASP.NET使用HttpWebRequest读取远程网页源代码

时间:2022-01-26 12:18:44

读取远程网页能做什么就不用多说了吧,做小偷程序或是采集,也就诸如此类了吧。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
public string GetPage(string url)
{
 
  HttpWebRequest request = null;
 
  HttpWebResponse response = null;
 
  StreamReader reader = null;
 
  try
  {
 
    request = (HttpWebRequest)WebRequest.Create(url);
 
    request.Timeout = 20000;
 
    request.AllowAutoRedirect = false;
 
    response = (HttpWebResponse)request.GetResponse();
 
    if (response.StatusCode == HttpStatusCode.OK && response.ContentLength < 1024 * 1024)
    {
 
      reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);
 
      string html = reader.ReadToEnd();
 
      return html;
 
    }
 
  }
 
  catch
  {
 
  }
 
  finally
  {
 
    if (response != null)
    {
 
      response.Close();
 
      response = null;
 
    }
 
    if (reader != null)
 
      reader.Close();
 
    if (request != null)
 
      request = null;
 
  }
 
  return string.Empty;
}