ahjesus HttpQuery

  1     /// <summary>
  2     /// 有关HTTP请求的辅助类
  3     /// </summary>
  4     public class HttpQuery
  5     {
  6         private static readonly string DefaultUserAgent =
  7             "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
  8
  9         public static void Get(string url, object data, Action<string> callback)
 10         {
 11             IDictionary<string, string> parameters = Getparameters(data);
 12
 13             if (!(parameters == null || parameters.Count == 0))
 14             {
 15                 url += "?";
 16                 foreach (var item in parameters)
 17                 {
 18                     url += item.Key + "=" + item.Value + "&";
 19                 }
 20             }
 21             CreateGetHttpResponse(url, null, null, null, callback);
 22         }
 23
 24         public static void Post(string url, object data, Action<string> callback)
 25         {
 26             IDictionary<string, string> parameters = Getparameters(data);
 27
 28             CreatePostHttpResponse(url, parameters, null, null, Encoding.UTF8, null, callback);
 29         }
 30
 31         public static void Post(string url, string data, Action<string> callback)
 32         {
 33             CreatePostHttpResponse(url, data, null, null, Encoding.UTF8, null, callback);
 34         }
 35
 36         private static IDictionary<string, string> Getparameters(object data)
 37         {
 38             if (data == null)
 39             {
 40                 return new Dictionary<string, string>();
 41             }
 42             IDictionary<string, string> parameters = new Dictionary<string, string>();
 43
 44             Type type = data.GetType();
 45             PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
 46             foreach (PropertyInfo p in props)
 47             {
 48                 parameters.Add(p.Name, p.GetValue(data).ToString());
 49             }
 50
 51             return parameters;
 52         }
 53
 54         /// <summary>
 55         /// 创建GET方式的HTTP请求
 56         /// </summary>
 57         /// <param name="url">请求的URL</param>
 58         /// <param name="timeout">请求的超时时间</param>
 59         /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
 60         /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
 61         /// <returns></returns>
 62         private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
 63             CookieCollection cookies, Action<string> callback, string encoding = "utf-8")
 64         {
 65             if (string.IsNullOrEmpty(url))
 66             {
 67                 return null;
 68                 //throw new ArgumentNullException("url");
 69             }
 70             try
 71             {
 72                 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
 73                 request.Method = "GET";
 74                 request.UserAgent = DefaultUserAgent;
 75                 if (!string.IsNullOrEmpty(userAgent))
 76                 {
 77                     request.UserAgent = userAgent;
 78                 }
 79                 if (timeout.HasValue)
 80                 {
 81                     request.Timeout = timeout.Value;
 82                 }
 83                 if (cookies != null)
 84                 {
 85                     request.CookieContainer = new CookieContainer();
 86                     request.CookieContainer.Add(cookies);
 87                 }
 88
 89                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
 90
 91                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
 92                     System.Text.Encoding.GetEncoding(encoding));
 93
 94                 string html = "";
 95                 //获取请求到的数据
 96                 html = reader.ReadToEnd();
 97                 //关闭
 98                 httpWebResponse.Close();
 99                 reader.Close();
100
101                 Regex regex = new Regex("charset=(?<code>\\w+)\"");
102                 Match match = regex.Match(html);
103                 string code = match.Groups["code"].Value;
104                 if (!string.IsNullOrWhiteSpace(code) && code.ToLower() != encoding.ToLower())
105                 {
106                     return CreateGetHttpResponse(url, timeout, userAgent, cookies, callback, code);
107                 }
108                 else
109                 {
110                     callback(html);
111                     return httpWebResponse;
112                 }
113             }
114             catch
115             {
116                 callback(null);
117             }
118             return null;
119         }
120
121         /// <summary>
122         /// 创建POST方式的HTTP请求
123         /// </summary>
124         /// <param name="url">请求的URL</param>
125         /// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
126         /// <param name="timeout">请求的超时时间</param>
127         /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
128         /// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
129         /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
130         /// <returns></returns>
131         private static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters,
132             int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)
133         {
134             if (string.IsNullOrEmpty(url))
135             {
136                 throw new ArgumentNullException("url");
137             }
138             if (requestEncoding == null)
139             {
140                 throw new ArgumentNullException("requestEncoding");
141             }
142             HttpWebRequest request = null;
143             try
144             {
145                 //如果是发送HTTPS请求
146                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
147                 {
148                     ServicePointManager.ServerCertificateValidationCallback =
149                         new RemoteCertificateValidationCallback(CheckValidationResult);
150                     request = WebRequest.Create(url) as HttpWebRequest;
151                     request.ProtocolVersion = HttpVersion.Version10;
152                 }
153                 else
154                 {
155                     request = WebRequest.Create(url) as HttpWebRequest;
156                 }
157                 request.Method = "POST";
158                 request.ContentType = "application/x-www-form-urlencoded";
159
160                 if (!string.IsNullOrEmpty(userAgent))
161                 {
162                     request.UserAgent = userAgent;
163                 }
164                 else
165                 {
166                     request.UserAgent = DefaultUserAgent;
167                 }
168
169                 if (timeout.HasValue)
170                 {
171                     request.Timeout = timeout.Value;
172                 }
173                 if (cookies != null)
174                 {
175                     request.CookieContainer = new CookieContainer();
176                     request.CookieContainer.Add(cookies);
177                 }
178                 //如果需要POST数据
179                 if (!(parameters == null || parameters.Count == 0))
180                 {
181                     StringBuilder buffer = new StringBuilder();
182                     int i = 0;
183                     foreach (string key in parameters.Keys)
184                     {
185                         if (i > 0)
186                         {
187                             buffer.AppendFormat("&{0}={1}", key, parameters[key]);
188                         }
189                         else
190                         {
191                             buffer.AppendFormat("{0}={1}", key, parameters[key]);
192                         }
193                         i++;
194                     }
195                     byte[] data = requestEncoding.GetBytes(buffer.ToString());
196                     using (Stream stream = request.GetRequestStream())
197                     {
198                         stream.Write(data, 0, data.Length);
199                     }
200                 }
201
202                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
203
204                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
205                     System.Text.Encoding.GetEncoding("utf-8"));
206
207                 string html = "";
208                 //获取请求到的数据
209                 html = reader.ReadToEnd();
210
211                 //关闭
212                 httpWebResponse.Close();
213                 reader.Close();
214
215                 callback(html);
216
217                 return httpWebResponse;
218             }
219             catch
220             {
221                 callback(null);
222             }
223             return null;
224         }
225
226         private static HttpWebResponse CreatePostHttpResponse(string url, string parameters, int? timeout,
227             string userAgent, Encoding requestEncoding, CookieCollection cookies, Action<string> callback)
228         {
229             if (string.IsNullOrEmpty(url))
230             {
231                 return null;
232                 //throw new ArgumentNullException("url");
233             }
234             if (requestEncoding == null)
235             {
236                 throw new ArgumentNullException("requestEncoding");
237             }
238             HttpWebRequest request = null;
239             try
240             {
241                 //如果是发送HTTPS请求
242                 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
243                 {
244                     ServicePointManager.ServerCertificateValidationCallback =
245                         new RemoteCertificateValidationCallback(CheckValidationResult);
246                     request = WebRequest.Create(url) as HttpWebRequest;
247                     request.ProtocolVersion = HttpVersion.Version10;
248                 }
249                 else
250                 {
251                     request = WebRequest.Create(url) as HttpWebRequest;
252                 }
253                 request.Method = "POST";
254                 request.ContentType = "application/x-www-form-urlencoded";
255
256                 if (!string.IsNullOrEmpty(userAgent))
257                 {
258                     request.UserAgent = userAgent;
259                 }
260                 else
261                 {
262                     request.UserAgent = DefaultUserAgent;
263                 }
264
265                 if (timeout.HasValue)
266                 {
267                     request.Timeout = timeout.Value;
268                 }
269                 if (cookies != null)
270                 {
271                     request.CookieContainer = new CookieContainer();
272                     request.CookieContainer.Add(cookies);
273                 }
274                 //如果需要POST数据
275                 if (!string.IsNullOrEmpty(parameters))
276                 {
277                     using (var streamWriter = new StreamWriter(request.GetRequestStream()))
278                     {
279                         streamWriter.Write(parameters);
280                         streamWriter.Flush();
281                     }
282                 }
283
284                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
285
286                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
287                     System.Text.Encoding.GetEncoding("utf-8"));
288
289                 string html = "";
290                 //获取请求到的数据
291                 html = reader.ReadToEnd();
292
293                 //关闭
294                 httpWebResponse.Close();
295                 reader.Close();
296
297                 callback(html);
298
299                 return httpWebResponse;
300             }
301             catch
302             {
303                 callback(null);
304             }
305             return null;
306         }
307
308         private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain,
309             SslPolicyErrors errors)
310         {
311             return true; //总是接受
312         }
313
314     }

使用方法

HttpQuery.Post(url, new { key = key, xmlCount = xmlCount }, (msg) =>
            {

            });
时间: 2024-08-04 09:46:34

ahjesus HttpQuery的相关文章

ahjesus linux连接阿里云ubuntu服务器并更改默认账号和密码,以及创建子账户

先确保本地Linux服务器SSH服务开启,如果没有开启直接执行指令:service sshd start 然后我们使用ssh指令进行远程登陆 ssh [email protected] 输入passwd指令修改旧密码 修改默认账号root vi /etc/passwd 按i键进入编辑状态 修改第1行第1个root为新的用户名 按esc键退出编辑状态,并输入:x保存并退出 vi /etc/shadow 按i键进入编辑状态 修改第1行第1个root为新的用户名 按esc键退出编辑状态,并输入:x!强

ahjesus SSHkey登陆linux服务器,无需密码,ubuntu

cd ~/.ssh/如果目录不存在就新建一个 mkdir ~/.ssh制作公匙 ssh-keygen -t rsa默认会生成id_rsa.pub的公匙将公匙推送到指定的服务器 scp id_rsa.pub [email protected]:~/.ssh/id_rsa.pub登录到服务器 ssh [email protected]执行如下命令cd ~/.sshcat id_rsa.pub >> authorized_keys销毁目录下公匙 rm id_rsa.pub退出服务器 exit 下次登

ahjesus 部署lighttpd

这个就不写了,直接传送门过去看,按照说的做就可以了 如果你想要安装最新版的,传送门 需要注意的是configure这一步,你看完他的help以后还要输入 ./configure 才能继续下一步 再就是svn获取不大稳定,如果连接失败就多获取几次,能成功的 ahjesus 部署lighttpd,码迷,mamicode.com

ahjesus fstab修改错误了如何修复

fstab修改错误了如何修复 当你不小心把磁盘表输入错误以后,系统总是让你按ctrl+D重新启动或者输入密 码进入shell,你输入密码登陆后, 编辑文件是只读的,执行下面的命令后就可以编辑了. mount -o remount,rw / vi /etc/fstab 删除错误的磁盘信息,重启就好了. ahjesus fstab修改错误了如何修复,布布扣,bubuko.com

ahjesus ubuntu10.4安装ruby2.1.1

sudo apt-get install python-software-properties sudo apt-add-repository ppa:brightbox/ruby-ng sudo apt-get update sudo apt-get install ruby2.1 ruby2.1 -v ruby 2.1.0p0 (2013-12-25 revision 44422) [x86_64-linux-gnu] ahjesus ubuntu10.4安装ruby2.1.1,码迷,mam

ahjesus配置vsftpd虚拟用户在Ubuntu

网上搜索了很多资料,过时,不全,货不对版 已下步骤亲测有效,不包含匿名用户登录 1.新建/home/loguser.txt 并填充内容,格式如下 用户名密码用户名密码用户名密码 2.生成db文件用于用户验证 执行db_load -T -t hash -f /home/loguser.txt /etc/vsftpd_login.db 如果没有装db会提示你apt-get install,根据提示的内容输入命令安装后再次执行生成db 3.设置数据库文件的访问权限 chmod 600 /etc/vsf

ahjesus 让我的MVC web API支持JsonP跨域

无数被跨域请求爆出翔来的人 遇到请求成功却不能进入success 总是提示parsererror 参考一下两篇文章吧 参考文章http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api and http://diaosbook.com/Post/2013/12/27/tips-for-aspnet-webapi-cors ahjesus 让我的MVC web API支持JsonP跨域

ahjesus用forever管理nodejs服务

全局安装forever npm install -g forever 查看帮助 forever -h 查看安装位置 whereis forever 编写自己的sh文件 forever -p web文件路径 -l 路径/access.log -e 路径/error.log -o 路径/out.log -a --pidFile 路径/app.pid start web文件路径/app.js 新建对应的路径和文件 启动服务 sh 我的配置.sh 根据提示知道启动成功了 更详细的操作请参考-h帮助 本文

ahjesus 前端缓存原理 转载

LAMP缓存图 从图中我们可以看到网站缓存主要分为五部分 服务器缓存:主要是基于web反向代理的静态服务器nginx和squid,还有apache2的mod_proxy和mod_cache模 浏览器缓存:包括页面html缓存和图片js,css等资源的缓存 PHP缓存:有很多免费的PHP缓冲加速工具,如apc eaccerlertor等 内存缓存:主要是采用memcache这种分布式缓存机制 数据库缓存:通过配置数据库缓存,以及数据存储过程,连接池技术等 下面重点介绍浏览器缓存原理: 从上图:我们