C# 對接騰訊企業郵接口----get/post請求

     在無所知之的狀況下、來了一個對接接口的任務,沒辦法,只能根據前端時候的經驗硬着頭皮上了,隨後又整理了一下寫的方法,主要包括了部門的建立、更新、刪除、查找、而後他們的前提是token的獲取html

    首先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,第一種沒有測試,應該沒問題。。我的以爲web

接下來我只貼出封裝的方法類,調用就本身寫吧。。json

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;
            }   
        }
    }
}

若是想要獲得其餘字段信息,就本身找個方法取出來吧。。。。api

其實摸透了,感受也就這樣。。。。cookie

相關文章
相關標籤/搜索