您的位置:首页 > 移动开发 > 微信开发

MVC 微信开发获取用户OpenID

2017-08-11 15:53 309 查看
1 public class HttpQuery {
2         private static readonly string DefaultUserAgent =
3             "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
4
5         public static void Get(string url, object data, Action<string> callback) {
6             IDictionary<string, string> parameters = Getparameters(data);
7
8             if (!(parameters == null || parameters.Count == 0)) {
9                 url += "?";
10                 foreach (var item in parameters) {
11                     url += item.Key + "=" + item.Value + "&";
12                 }
13             }
14             CreateGetHttpResponse(url, null, null, null, callback);
15         }
16         /// <summary>
17         /// 创建GET方式的HTTP请求
18         /// </summary>
19         /// <param name="url">请求的URL</param>
20         /// <param name="timeout">请求的超时时间</param>
21         /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
22         /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
23         /// <returns></returns>
24         private static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent,
25             CookieCollection cookies, Action<string> callback, string encoding = "utf-8") {
26             if (string.IsNullOrEmpty(url)) {
27                 return null;
28                 //throw new ArgumentNullException("url");
29             }
30             try {
31                 HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
32                 request.Method = "GET";
33                 request.UserAgent = DefaultUserAgent;
34                 if (!string.IsNullOrEmpty(userAgent)) {
35                     request.UserAgent = userAgent;
36                 }
37                 if (timeout.HasValue) {
38                     request.Timeout = timeout.Value;
39                 }
40                 if (cookies != null) {
41                     request.CookieContainer = new CookieContainer();
42                     request.CookieContainer.Add(cookies);
43                 }
44
45                 HttpWebResponse httpWebResponse = request.GetResponse() as HttpWebResponse;
46
47                 StreamReader reader = new StreamReader(httpWebResponse.GetResponseStream(),
48                     System.Text.Encoding.GetEncoding(encoding));
49
50                 string html = "";
51                 //获取请求到的数据
52                 html = reader.ReadToEnd();
53                 //关闭
54                 httpWebResponse.Close();
55                 reader.Close();
56
57                     callback(html);
58                     return httpWebResponse;
59                 }
60             } catch {
61                 callback(null);
62             }
63             return null;
64         }
65
66 }


Http GET请求
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: