• .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
  • 相关阅读:
    搭建Java 开发环境
    自己制作 Android Vector Asset 矢量图
    Manifest merger failed with multiple errors, see logs 问题处理
    Android 获取所在城市(不接入地图SDK,使用android自带的SDK定位)
    根据视频地址获取封面
    Git 的一些使用细枝末节
    关于onActivityResult方法不执行的问题汇总
    关于handler 和 looper 的问题
    关于action和category的认知区别
    关于activity的生命周期的随笔
  • 原文地址:https://www.cnblogs.com/sdya233/p/14312251.html
Copyright © 2020-2023  润新知