zoukankan      html  css  js  c++  java
  • .Net 后台访问接口获取数据

     

     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 }
    View Code
  • 相关阅读:
    day12. 闭包
    day11.函数的全局变量和局部变量
    day10.函数基础及函数参数
    day9.关于文件的操作
    day7.关于字符串的相关操作
    day8.列表、字典、集合相关操作
    day6. while双项循环及for循环
    LeetCode-Unique Binary Search Trees II
    LeetCode-Unique Binary Search Trees
    LeetCode-Edit Distance
  • 原文地址:https://www.cnblogs.com/sdya233/p/14312251.html
Copyright © 2011-2022 走看看