说明:一个用C#编写的WebAPI操作类,只写了Get Post 部分。
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; namespace Assets.Scripts.Models { class WebAPIOperator { static string ip = ConfigMan.ReadNode("ServerSet", "ip"); static string port = ConfigMan.ReadNode("ServerSet", "port"); static string baseUri = "http://" + ip + ":" + port; /// <summary> /// 服务器通信状态 /// </summary> public static bool NetState = true; public static HttpClient httpClient; #region CTOR private WebAPIOperator() { httpClient.BaseAddress = new Uri(baseUri); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json")); } #endregion #region Async Task public static async Task RunAsync() { httpClient.BaseAddress = new Uri(baseUri); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json")); try { //执行API任务 } catch (Exception) { throw; } } #endregion #region init public static void initAPI() { ip = ConfigMan.ReadNode("ServerSet", "ip"); port = ConfigMan.ReadNode("ServerSet", "port"); baseUri = "http://" + ip + ":" + port; httpClient = new HttpClient(); httpClient.BaseAddress = new Uri(baseUri); httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json")); //系统默认超时100s //https://docs.microsoft.com/zh-cn/dotnet/api/system.net.http.httpclient.timeout?view=netframework-4.8#System_Net_Http_HttpClient_Timeout //httpClient.Timeout = TimeSpan.FromMinutes(1);//超时60s } #endregion #region Get /// <summary> /// WebAPI Get方法,返回JObject /// </summary> /// <param name="uri">带参数的uri</param> /// <returns></returns> public static async Task<JObject> GetAsync(string uri) { JObject o = null; try { HttpResponseMessage response = new HttpResponseMessage(); response = await httpClient.GetAsync(uri); if (response != null && response.IsSuccessStatusCode) { string jsonStr = await response.Content.ReadAsStringAsync();//获取JSON字符串 JObject jobj = JObject.Parse(jsonStr);//转换为JObject //o=... //保存数据到文件等 //List_Screen.Items.Add(jsonStr); o = jobj; NetState = true; } else { NetState = false; } } catch (Exception ex) { Console.WriteLine(ex.Message); //更新网络状态 NetState = false; //Log4NetHelper.Error("网络掉线", ex); } return o; } /// <summary> /// WebAPI GET方法,返回string json,用于反序列化 /// </summary> /// <param name="uri"></param> /// <returns></returns> public static async Task<string> GetAsync_uri(string uri) { string jsonStr = ""; try { HttpResponseMessage response = await httpClient.GetAsync(uri); if (response.IsSuccessStatusCode) { jsonStr = await response.Content.ReadAsStringAsync();//获取JSON字符串 //JObject jobj = JObject.Parse(jsonStr);//转换为JObject //o=... //保存数据到文件等 //List_Screen.Items.Add(jsonStr); //o = jobj; } NetState = true; } catch (Exception ex) { Console.WriteLine(ex.Message); //更新网络状态 NetState = false; //RoutedEventArgs args = new RoutedEventArgs(UpdateNetStateEvent); //new ImageButton().RaiseEvent(args); //Log4NetHelper.Error("网络掉线", ex); } return jsonStr; } #endregion #region POST public static async Task<string> PostAsync(string uri, Object obj) { string o = ""; string jsonStr = JsonConvert.SerializeObject(obj); HttpResponseMessage response = await httpClient.PostAsJsonAsync<Object>(uri, obj); //response.EnsureSuccessStatusCode();//响应失败时,用于触发异常 //return response.Headers.Location; if (response.IsSuccessStatusCode) { //string jsonStr = await response.Content.ReadAsStringAsync();//获取JSON字符串 //JObject jobj = JObject.Parse(jsonStr); //o = jobj; //o = await response.Content.ReadAsAsync<object>(); o = await response.Content.ReadAsStringAsync(); } return o; } public static async Task<object> PostAsync(string uri, string userName, string password) { Object o = null; HttpContent httpContent = new StringContent("loginName=" + userName + "&password=" + password); httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); HttpResponseMessage response = await httpClient.PostAsync(uri, httpContent); if (response.IsSuccessStatusCode) { string jsonStr = await response.Content.ReadAsStringAsync();//获取JSON字符串 JObject jobj = JObject.Parse(jsonStr); o = jobj; } return o; } #endregion #region PUT //static async Task<Object> PutAsync(string uri, Object o) //{ // HttpResponseMessage response = await httpClient.PutAsJsonAsync<Object>(uri + "//id=" + 123, o); // response.EnsureSuccessStatusCode(); // o = await response.Content.ReadAsAsync<Object>(); // return o; } #endregion #region Delete //static async Task<HttpStatusCode> DeleteAsync(string uri, string id) //{ // HttpResponseMessage response = await httpClient.DeleteAsync(uri + "//" + id); // return response.StatusCode; //} #endregion }