1:Get: web
public static string HttpGetJsonAPI(string uri) { try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); webRequest.Method = "GET"; webRequest.ContentType = "application/json"; webRequest.Accept = "application/json"; webRequest.Headers.Add("Authorization", GlobalVariable.NowLoginUser.JwtKey); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8); String res = reader.ReadToEnd(); reader.Close(); return res.Trim(); } catch (Exception ex) { return null; } }
2:Post:json
public static string HttpPostJsonAPI(string uri, string parameters,string Type, string token = "") { try { byte[] bytes = Encoding.UTF8.GetBytes(parameters);//這裏須要指定提交的編碼 HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uri); webRequest.Method = "POST"; webRequest.ContentType = "application/json"; webRequest.Accept = "application/json"; if (GlobalVariable.NowLoginUser == null) webRequest.Headers.Add("token", ""); else webRequest.Headers.Add("token", GlobalVariable.NowLoginUser.JwtKey); webRequest.ContentLength = bytes.Length; Stream dataStream = webRequest.GetRequestStream(); dataStream.Write(bytes, 0, bytes.Length); dataStream.Close(); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); StreamReader reader = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8); String res = reader.ReadToEnd(); reader.Close(); return res.Trim(); } catch (Exception ex) { return null; } }
3:將獲取到的數據轉換爲相應實體類:api
public static List<T> GetData<T>(Dictionary<string, string> dicNamwValue, string FunTitile, EnumWebType enumType) { try { string strurl = GlobalVariable.WebRemotelyIP + FunTitile;// ; List<T> listPcaSumData = new List<T>(); foreach (var item in dicNamwValue) { strurl = strurl + item.Key + "=" + item.Value + "&"; } strurl = strurl.Substring(0, strurl.LastIndexOf("&")); string strapi = null; if (enumType == EnumWebType.Get) strapi = HttpGetJsonAPI(strurl); else strapi = HttpPostJsonAPI(strurl, string.Empty, EnumWebType.Post.ToString()); if (strapi != null) { JObject json1 = (JObject)JsonConvert.DeserializeObject(strapi); JValue jTotalCount = (JValue)json1[OrigriUserInfo.totalCount]; Type tokenType = json1[OrigriUserInfo.data].GetType(); switch (tokenType.FullName) { case "Newtonsoft.Json.Linq.JArray": JArray array = (JArray)json1[OrigriUserInfo.data]; foreach (var jObject in array) { listPcaSumData.Add(JsonConvert.DeserializeObject<T>(jObject.ToString())); } break; case "Newtonsoft.Json.Linq.JValue": JValue jdata = (JValue)json1[OrigriUserInfo.data]; listPcaSumData.Add(JsonConvert.DeserializeObject<T>(jdata.ToString())); break; } return listPcaSumData; } else return null; } catch (Exception ex) { return null; } }