1 ///
2 ///POST时用到的几个数据3 ///
4 public structPostData5 {6 ///
7 ///目标服务器地址8 ///
9 public stringurl;10 ///
11 ///采用的编码12 ///
13 public stringencoding;14 ///
15 ///POST的数据16 ///
17 public stringcontentData;18 ///
19 ///contentType20 ///
21 public stringcontentType;22 ///
23 ///添加其他的Header24 ///
25 public stringheader;26 }27
28 ///
29 ///申请腾讯企业邮箱时的管理员账户30 ///
31 string client_id = "hhhhhhhhhhh.com";32 ///
33 ///腾讯企业邮箱分配的接口key34 ///
35 string client_secret = "3ed4b10okd37f2e0f56f23a3b6e53013";36 ///
37 ///目标邮箱的账户,获取对应的未读邮件数38 ///
39 string alias = "chen123@hhhhhhhhhhh.com";40
41 ///
42 ///按钮事件,调用腾讯API获取Token,然后获取未读邮件数43 ///
44 ///
45 ///
46 private void bNewMailCount_Click(objectsender, EventArgs e)47 {48 //第一步获取Token
49 PostData pdata = newPostData();50 pdata.url = "https://tel.exmail.qq.com/cgi-bin/token";51 pdata.contentData = "grant_type=client_credentials&client_id=" + client_id + "&client_secret=" +client_secret;52 pdata.encoding = "UTF-8";53 pdata.contentType = "application/x-www-form-urlencoded";54
55 string responseString = "";56 //获取token_type和access_token
57 LitJson.JsonData json = this.Post(pdata, outresponseString);58
59 if (json != null)60 {61 //获取Token成功后,第二步,获取未读邮件数
62 pdata = newPostData();63 pdata.url = "http://openapi.exmail.qq.com:12211/openapi/mail/newcount";64 pdata.contentData = "alias=" +alias;65 pdata.encoding = "UTF-8";66 pdata.contentType = "application/x-www-form-urlencoded";67 pdata.header = "Authorization:" + json["token_type"] + " " + json["access_token"];68
69 responseString = "";70 json = this.Post(pdata, outresponseString);71
72 if (json != null)73 {74 responseString = "账户:" + json["Alias"] + "未读邮件:" + json["NewCount"];75 iHandler.TextBoxAppend(this.tResponse, responseString, true);76 }77 }78 }79 ///
80 ///POST,返回LitJson.JsonData对象81 ///
82 ///
83 ///
84 ///
85 private LitJson.JsonData Post(PostData pdata, out stringresponseString)86 {87 responseString =String.Empty;88 try
89 {90 Encoding encoding =Encoding.GetEncoding(pdata.encoding);91 byte[] data =encoding.GetBytes(pdata.contentData);92 HttpWebRequest webReq =(HttpWebRequest)WebRequest.Create(pdata.url);93 webReq.Method = "POST";94 webReq.ContentLength =data.Length;95 webReq.ContentType = pdata.contentType + "; charset=" +pdata.encoding;96 if (!String.IsNullOrEmpty(pdata.header))97 {98 webReq.Headers.Add(pdata.header);99 }100 Stream webStream =webReq.GetRequestStream();101 webStream.Write(data, 0, data.Length);102
103 WebResponse webResp =webReq.GetResponse();104 Stream webRespStream =webResp.GetResponseStream();105 StreamReader reader = newStreamReader(webRespStream, encoding);106 string respXml =reader.ReadToEnd();107 reader.Close(); reader.Dispose();108 webResp.Close();109
110 responseString =respXml;111 returnLitJson.JsonMapper.ToObject(respXml); ;112 }113 catch(Exception ex)114 {115 responseString =ex.ToString();116 return null;117 }118 }