forked from xuxiaowei007/FoxOne
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHttpHelper.cs
93 lines (90 loc) · 3.18 KB
/
HttpHelper.cs
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
namespace FoxOne.Core
{
public static class HttpHelper
{
public static void GetImage(string imgUrl, string imgPath)
{
var url = HttpContext.Current.Request.Url;
WebClient client = new WebClient();
FileInfo dirInfo = new FileInfo(imgPath);
string acceptExts = ".js|.css|.jpg|.png|.bmp|.jpeg|.html|.ico|.gif";
if (acceptExts.Split('|').Contains(dirInfo.Extension))
{
if (!dirInfo.Directory.Exists)
{
dirInfo.Directory.Create();
}
try
{
client.DownloadFile(imgUrl, imgPath);
}
catch
{
}
}
}
public static string GetContent(string url, IDictionary<string, object> parameter = null)
{
try
{
url = BuildUrl(url, parameter);
var MyWebClient = new WebClient();
MyWebClient.Credentials = CredentialCache.DefaultCredentials; //获取或设置用于向Internet资源的请求进行身份验证的网络凭据
Byte[] pageData = MyWebClient.DownloadData(url); //从指定网站下载数据
//string pageHtml = System.Text.Encoding.Default.GetString(pageData);//如果获取网站页面采用的是GB2312,则使用这句
string pageHtml = Encoding.UTF8.GetString(pageData); //如果获取网站页面采用的是UTF-8,则使用这句
return pageHtml;
}
catch (WebException webEx)
{
Console.WriteLine(webEx.Message.ToString());
return null;
}
}
public static string BuildUrl(string url, HttpRequestBase request)
{
if (request == null || string.IsNullOrEmpty(url))
{
return url;
}
foreach (var p in request.QueryString.AllKeys)
{
if (url.IndexOf('?') > 0)
{
url += string.Format("&{0}={1}", p, request.QueryString[p]);
}
else
{
url += string.Format("?{0}={1}", p, request.QueryString[p]);
}
}
return url;
}
public static string BuildUrl(string url, IDictionary<string, object> parameters)
{
if (parameters.IsNullOrEmpty() || string.IsNullOrEmpty(url))
{
return url;
}
foreach (var p in parameters)
{
if (url.IndexOf('?') > 0)
{
url += string.Format("&{0}={1}", p.Key, p.Value);
}
else
{
url += string.Format("?{0}={1}", p.Key, p.Value);
}
}
return url;
}
}
}