隐藏

C# 调用外部api接口获取数据

发布:2020/3/4 1:58:25作者:管理员 来源:本站 浏览次数:1139

public LoginResult Login()
        {
            LoginParam param = new LoginParam
            {
                userName = "zhangsan",
                password = "000000"
            };

            LoginResult rdata = new LoginResult();
            Stream cResponseStream = null;
            HttpClient cHttpClient = null;
            HttpContent cHttpContent = null;
            StreamReader cStreamReader = null;
            HttpResponseMessage cResponse = null;
            HttpClientHandler cHttpHandler = null;
            string sJson = "";
            string sHttpUrl = "http://192.168.1.132:8020/api/user/login";
            try
            {

                cHttpHandler = new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.GZip };
                cHttpClient = new HttpClient(cHttpHandler);
                cHttpClient.Timeout = new TimeSpan(0, 0, 10);

                sJson = JsonConvert.SerializeObject(param);
                cHttpContent = new StringContent(sJson);
                cHttpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                cHttpContent.Headers.ContentLength = (Encoding.UTF8.GetBytes(sJson)).Length;

                Task<HttpResponseMessage> cResponseTask = cHttpClient.PostAsync(sHttpUrl, cHttpContent);
                cResponseTask.Wait();
                if (cResponseTask.Result != null)
                {
                    cResponse = cResponseTask.Result;
                    if (cResponse.IsSuccessStatusCode)
                    {
                        Task<Stream> cResponseStreamTask = cResponseTask.Result.Content.ReadAsStreamAsync();
                        cResponseStreamTask.Wait();
                        if (cResponseStreamTask.Result != null)
                        {
                            cResponseStream = cResponseStreamTask.Result;
                            cStreamReader = new StreamReader(cResponseStream, Encoding.UTF8);
                            var Result = cStreamReader.ReadToEnd();
                            JObject jo = (JObject)JsonConvert.DeserializeObject(Result);
                            var nRet = jo.ToString();//如果要解析里面的某个实体对象:((JObject)jo["data"]).toString();//data是对应的字段名称
                            rdata = DeserializeJsonToObject<LoginResult>(nRet);
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                if (cResponseStream != null)
                {
                    cResponseStream.Close();
                    cResponseStream.Dispose();
                }
                if (cStreamReader != null)
                {
                    cStreamReader.Close();
                    cStreamReader.Dispose();
                }
                if (cResponse != null) cResponse.Dispose();
                if (cHttpHandler != null) cHttpHandler.Dispose();
                if (cHttpClient != null) cHttpClient.Dispose();
            }
            return rdata;
        }

        /// <summary>
        /// 解析JSON字符串生成对象实体
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="json">json字符串(eg.{"ID":"112","Name":"石子儿"})</param>
        /// <returns>对象实体</returns>
        public static T DeserializeJsonToObject<T>(string json) where T : class
        {
            try
            {
                JsonSerializer serializer = new JsonSerializer();
                StringReader sr = new StringReader(json);
                object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
                T t = o as T;
                return t;
            }
            catch (Exception)
            {
                return null;
            }
        }

 

另:返回值LoginResult类对应外部接口返回的数据构建的实体类:

public class LogionResult{

      public int status;//状态码

      public string info;//错误信息

      public UserInfo data;//用户信息实体类

}
————————————————
版权声明:本文为CSDN博主「000wen_Android」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/aiguoguo000/article/details/88850679