C# 請求Web Api 接口,返回的json數據直接反序列化爲實體類

需要的引用的dll類:

Newtonsoft.Json.dll、System.Net.Http.dll、System.Net.Http.Formatting.dll



Web Api接口爲GET形式:

 public static CstyleCmappListRespDTO GetCstyleCmappList(string cstylename, string cmappgname)
        {
            CstyleCmappListRespDTO RespDTO = new CstyleCmappListRespDTO();
            var url = string.Empty;
            try
            {
                url = RequestUrl + "/dw/get_cstylecmappg_info_dw?id={0}&key={1}×tamp={2}&cstylename={3}&cmappgname={4}";
                url = string.Format(url, id, key, DateTime.Now.ToString("yyyyMMddHHmmss"), cstylename, cmappgname);
                var httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.GetAsync(new Uri(url)).Result;
                RespDTO = response.Content.ReadAsAsync<CstyleCmappListRespDTO>().Result;
            }
            catch (Exception ex)
            {
                
            }
            return RespDTO;
        }

Web Api接口爲POST形式:

public static FlightsResponse QueryFlightPost(FlightQueryRequest ReqDTO)
        {
            FlightsResponse FlightsRespDTO = new FlightsResponse();
            try
            {
                string requestDTO = JsonConvert.SerializeObject(ReqDTO);
                MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
                HttpContent httpContent = new ObjectContent<FlightQueryRequest>(ReqDTO, jsonFormatter);
                var url = RequestUrl + "/QueryFlight";
                var httpClient = new HttpClient(new RequestHandler() { InnerHandler = new HttpClientHandler() });
                httpClient.Timeout = TimeSpan.FromMinutes(3);
                var responseJson = httpClient.PostAsync(url, httpContent).Result;
                FlightsRespDTO = responseJson.Content.ReadAsAsync<FlightsResponse>().Result;
                
            }
            catch (Exception)
            {
                FlightsRespDTO = new FlightsResponse();
            }
            return FlightsRespDTO;
        }







發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章