/// <summary> ///接口获取openid和session_key /// </summary> /// <param name="code">前台通过调用login接口获取到的code</param> /// <param name="anonymous_code">前台通过调用login接口获取到的anonymous_code</param> /// <returns></returns> public string LoginGetopenid(string code, string anonymous_code)//未效验 { //按照规则填写参数 string appid = "***********"; string secret = "*****************************************"; //地址(这里对地址和参数进行了分开处理,url为地址,postString为参数) string url = "https://developer.toutiao.com/api/apps/jscode2session"; //这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进来 string GETString = "appid=" + appid + "&secret=" + secret + "&code=" + code + "&anonymous_code=" + anonymous_code; //编码,尤其是汉字,事先要看下抓取网页的编码方式 byte[] GETData = Encoding.UTF8.GetBytes(GETString); //初始化WebClient类(提供将数据发送到url的资源,及从这样的资源接收数据) WebClient webClient = new WebClient(); ////采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可 //webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); string requestUrl = url + "?" + GETString; //得到解码的返回字符流 string responseData = Encoding.UTF8.GetString(webClient.DownloadData(requestUrl)); //解码后将数据转换为Json类型的object JObject returnJSON = (JObject)JsonConvert.DeserializeObject(responseData); //赋值如果未获取到openid则登录失败,否则成功 dynamic objJson = new ExpandoObject(); if (returnJSON["openid"] != null || returnJSON["openid"].ToString() != "") { int error = Convert.ToInt32(returnJSON["error"]); string openid = returnJSON["openid"].ToString(); string session_key = returnJSON["session_key"].ToString(); string anonymous_openid = returnJSON["anonymous_openid"].ToString(); } else { //为空则返回失败 } return “”; }