首页 > 代码库 > WebClient 调用api

WebClient 调用api

使用:
  /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public static string GetUserInfo(string code, string accessToken)
        {
            string userid = "";
            string url = oApiHost + "/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
            string result = Tool.HttpGet(url);

            dynamic data = http://www.mamicode.com/JsonConvert.DeserializeObject<dynamic>(result);


            if (data.errcode == 0)
            {
                userid = data.userid;
            }
            else
            {
                throw new Exception("获取User Id发生错误,钉钉返回:" + Convert.ToString(data.errmsg));
            }
            return userid;
        }

 

Tool类:

 public class Tool
    {
        public static string HttpGet(string url)
        {
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json");
            client.Encoding = Encoding.UTF8;
            string result = client.DownloadString(url);
            return result;
        }

        public static string HttpPost(string url, NameValueCollection data)
        {
            WebClient client = new WebClient();
            client.Headers.Add("Content-Type", "application/json");
            client.Encoding = Encoding.UTF8;
            byte[] origin_result = client.UploadValues(url, data);
            return Encoding.UTF8.GetString(origin_result);
        }
}

 

 

WebClient 调用api