标签:thread nbsp rtm 返回 table manage lld namespace 默认
在无所知之的情况下、来了一个对接接口的任务,没办法,只能根据前端时候的经验硬着头皮上了,随后又整理了一下写的方法,主要包括了部门的创建、更新、删除、查找、然后他们的前提是token的获取
首先HTTPHelper类
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Net; using System.Net.Security; using System.Security.Cryptography.X509Certificates; namespace Name_HttpHelper { public class HttpHelper { /// <summary> /// 创建GET方式的HTTP请求 /// </summary> public HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies) { HttpWebRequest request = null; if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true) ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; //http版本,默认是1.1,这里设置为1.0 } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "GET"; //设置代理UserAgent和超时 //request.UserAgent = userAgent; //request.Timeout = timeout; if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } return request.GetResponse() as HttpWebResponse; } /// <summary> /// 创建POST方式的HTTP请求 /// </summary> public HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies) { HttpWebRequest request = null; //如果是发送HTTPS请求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; //设置代理UserAgent和超时 //request.UserAgent = userAgent; //request.Timeout = timeout; if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //发送POST数据 if (!(parameters == null || parameters.Count == 0)) { StringBuilder buffer = new StringBuilder(); int i = 0; foreach (string key in parameters.Keys) { if (i > 0) { buffer.AppendFormat("&{0}={1}", key, parameters[key]); } else { buffer.AppendFormat("{0}={1}", key, parameters[key]); i++; } } byte[] data = Encoding.ASCII.GetBytes(buffer.ToString()); using (Stream stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } } string[] values = request.Headers.GetValues("Content-Type"); return request.GetResponse() as HttpWebResponse; } //post方式2---传递json字符串作为post结构体 public string SendDataByPost(string Url, string postDataStr, ref CookieContainer cookie) { // Logger.Info("请求信息:" + url + param); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(Url); request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded"; request.Accept = "*/*"; request.Timeout = 10000; request.AllowAutoRedirect = false; byte[] bs = Encoding.UTF8.GetBytes(postDataStr); request.ContentLength = bs.Length; string responseStr = null; try { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback ( delegate { return true; } ); var s = request.GetRequestStream(); s.Write(bs, 0, bs.Length); s.Close(); WebResponse myWebResponse = request.GetResponse(); using (StreamReader sr = new StreamReader(myWebResponse.GetResponseStream(), Encoding.UTF8)) { // 返回结果 responseStr = sr.ReadToEnd(); } } catch (Exception ex) { // Logger.Error(ex.Message + "\r\t\n" + ex.StackTrace); } finally { request = null; } //Logger.Info("请求结果:" + responseStr); return responseStr; } /// <summary> /// 获取请求的数据 /// </summary> public static string GetResponseString(HttpWebResponse webresponse) { using (Stream s = webresponse.GetResponseStream()) { StreamReader reader = new StreamReader(s, Encoding.UTF8); return reader.ReadToEnd(); } } /// <summary> /// 验证证书 /// </summary> private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { if (errors == SslPolicyErrors.None) return true; return false; } } }
这里我post方式用的方式2,第一种没有测试,应该没问题。。个人觉得
接下来我只贴出封装的方法类,调用就自己写吧。。
using Name_HttpHelper; using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace AllActions { public class HttpAction { /* * 功能:创建部门 * 参数:token 调用接口凭证, name 部门名称, * parentid 父部门id, order 在目录中的排序 * 返回:string 创建结果 */ public string CreateDepartmentAction(string token, string name, long parentid, int order) { string url = "https://api.exmail.qq.com/cgi-bin/department/create?access_token=" + token; Encoding encoding = Encoding.GetEncoding("utf-8"); string jsonStr = "{" + string.Format("\"name\": \"{0}\",\"parentid\": {1},\"order\": {2}", name, parentid, order) + "}"; CookieContainer cookie = new CookieContainer(); HttpHelper hh = new HttpHelper(); string s = hh.SendDataByPost(url, jsonStr, ref cookie); return s; } /* * 功能:更新部门信息 * 参数:token 调用接口凭证, name 更新的部门名称, * parentid 父部门id,为1可表示根部门 order 在目录中的排序, * id 必填 部门id * 返回:string 更新结果 */ public string UpdateDepartmentAction(string token, string name, long parentid, int order, long id) { string url = "https://api.exmail.qq.com/cgi-bin/department/update?access_token=" + token; Encoding encoding = Encoding.GetEncoding("utf-8"); string jsonStr = "{" + string.Format("\"name\": \"{0}\",\"parentid\": {1},\"order\": {2},\"id\":{3}", name, parentid, order, id) + "}"; CookieContainer cookie = new CookieContainer(); HttpHelper hh = new HttpHelper(); string s = hh.SendDataByPost(url, jsonStr, ref cookie); return s; } /* * 功能:查找部门信息 * 参数:token 调用接口凭证, * name 查找部门名称, * fuzzy 1/0:是否模糊匹配 * 返回:string 更新结果 */ public string SelectSpecialDepartmentAction(string token, string name, int fuzzy) { string url = "https://api.exmail.qq.com/cgi-bin/department/search?access_token=" + token; Encoding encoding = Encoding.GetEncoding("utf-8"); string jsonStr = "{" + string.Format("\"name\": \"{0}\",\"fuzzy\": {1}", name, fuzzy) + "}"; CookieContainer cookie = new CookieContainer(); HttpHelper hh = new HttpHelper(); string s = hh.SendDataByPost(url, jsonStr, ref cookie); return s; } /* * 功能:删除部门 * 参数:部门id */ public string DeleteDepartmentAction(string token, long id) { string url = "https://api.exmail.qq.com/cgi-bin/department/delete?access_token=" + token + "&id=" + id; CookieCollection cookie = new CookieCollection(); int Tag = 1; string dataStr = HttpResponeTypeByGet(url, 20000, null, cookie,Tag); return dataStr; } /* * 功能:获取调用接口的凭证 access_token * 参数:corpid 企业id 必填 * corpsecret 应用的凭证密钥 必填 */ public string GetAccessTokenAction(string corpid, string corpsecret) { string url = "https://api.exmail.qq.com/cgi-bin/gettoken?corpid=" + corpid + "&corpsecret=" + corpsecret; CookieCollection cookie = new CookieCollection(); int Tag = 100; string tokenStr = HttpResponeTypeByGet(url, 20000, null, cookie,Tag); return tokenStr; } /* * 功能:获取部门列表 * 参数:access_token 调用接口凭证 * id 部门id。获取指定部门及其下的子部门。id为1时可获取根部门下的子部门。 */ public string SelectAllDepartmentAction(string token, long id) { string url = " https://api.exmail.qq.com/cgi-bin/department/list?access_token=" + token + "&id=" + id; CookieCollection cookie = new CookieCollection(); int Tag = 2; string dataStr = HttpResponeTypeByGet(url, 20000, null, cookie,Tag); return dataStr; } //get方式获取请求结果 public string HttpResponeTypeByGet(string url, int timeout, string userAgent, CookieCollection cookies,int Tag) { HttpHelper hh = new HttpHelper(); //string url, int timeout, string userAgent, CookieCollection cookies HttpWebResponse response = hh.CreateGetHttpResponse(url, timeout, null, cookies); //打印返回值 Stream stream = response.GetResponseStream(); //获取响应的字符串流 StreamReader sr = new StreamReader(stream); //创建一个stream读取流 string html = sr.ReadToEnd(); //从头读到尾,放到字符串html if (Tag == 100)//获取token值 { //解析数据(请求返回的结果) string str = html.Replace(@"""", "").Replace("{", "").Replace("}", ""); string strTemp = ""; Hashtable ta = new Hashtable(); for (int i = 0; i < str.Split(‘,‘).Length; i++) { //< span style = "white-space:pre" > </ span > strTemp = str.Split(‘,‘)[i].ToString(); Console.WriteLine(strTemp); ta.Add(strTemp.Split(‘:‘)[0], strTemp.Split(‘:‘)[1]); } Console.WriteLine(ta); string token = ta["access_token"].ToString();//取出哈希表中的字段的值 return token; } else//其他情况 { return html; } } } }
如果想要得到其他字段信息,就自己找个方法取出来吧。。。。
其实摸透了,感觉也就这样。。。。
标签:thread nbsp rtm 返回 table manage lld namespace 默认
原文地址:http://www.cnblogs.com/oceanHeart-yang/p/6501705.html