1 private AccessToken GetAccessToken(string strUrl) { 2 //令牌类 可换成请求的实体类 3 AccessToken token = new AccessToken(); 4 //try { 5 string szdw = System.Web.Configuration.WebConfigurationManager.AppSettings["placeNumber"].ToString(); 6 string secret = System.Web.Configuration.WebConfigurationManager.AppSettings["secret"].ToString(); 7 //请求接口 最好配置到webconfig 8 strUrl = strUrl + "api/index?action=token_getAccessToken"; 9 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(strUrl); 10 //设置请求参数 11 string json = new JavaScriptSerializer().Serialize(new { 12 secret = secret, 13 szdw = szdw 14 }); 15 //设置请求方式 16 webRequest.ContentType = "application/json"; 17 webRequest.Accept = "application/json"; 18 webRequest.Method = "POST"; 19 //传参 20 byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes(json); 21 Stream requestStream = webRequest.GetRequestStream(); 22 requestStream.Write(buffer, 0, buffer.Length); 23 requestStream.Close(); 24 //发送请求,等待服务器返回 25 var httpResponse = (HttpWebResponse)webRequest.GetResponse(); 26 //将字节流包装为高级的字符流,以便于读取文本内容 27 using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { 28 //读取响应内容 29 var result = streamReader.ReadToEnd(); 30 //数据反序列化变成可读取数据 31 JObject jo = (JObject)JsonConvert.DeserializeObject(result); 32 token.code = jo["code"].ToString(); 33 token.msg = jo["msg"].ToString(); 34 token.expireTime = jo["expire_time"].ToString(); 35 token.accessToken = jo["access_token"].ToString(); 36 //创建文件夹 获取请求日志到本地 37 string sPath = @"C:xsoft"; 38 if (!Directory.Exists(sPath)) { 39 Directory.CreateDirectory(sPath); 40 } 41 FileStream fs1 = new FileStream(sPath + "data.txt", FileMode.Create, FileAccess.Write); 42 StreamWriter sw1 = new StreamWriter(fs1); 43 sw1.WriteLine(jo["code"].ToString() + jo["msg"].ToString()); 44 sw1.Close(); 45 fs1.Close(); 46 } 47 return token; 48 }