using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Runtime.Serialization.Json; using System.Text; using System.Threading; namespace WIDESEA_Core.Utilities { public enum RequestMethod { Get = 1,//获取 Post = 2,//投寄 OPTIONS = 3,//选项 HEAD = 4,//头 PUT = 5,//放置 DELETE = 6,//删除 TRACE = 7,//跟踪 CONNECT = 8,//连接 } public class WebApiHelper { //internal static string MesBlankDownAddress = Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["MesBlankDown"]); //application/x-www-form-urlencoded//application/json /// /// webapi地址调用函数 /// /// 地址 /// 验证用户 /// 请求方式 /// 参数(json) /// public static JObject SendInfoToWebAPI(string url, string user_Id = null, string reqMethod = "Get", JArray param = null) { //JArray jsonobj =new JArray(); JObject jobj = null; HttpWebRequest webRequest = null; HttpWebResponse webResponse = null; try { Thread.Sleep(3500); webRequest = (HttpWebRequest)HttpWebRequest.Create(url); //webRequest.ContentType = "application/x-www-form-urlencoded"; //webRequest.ContentType = "application/json"; string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); webRequest.ContentType = "multipart/form-data; boundary=" + boundary; //webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727) "; webRequest.Method = reqMethod; webRequest.AllowAutoRedirect = false; webRequest.Timeout = 50000; byte[] PostData = null; if (user_Id != null) webRequest.Headers.Add("Authorization", user_Id); //webRequest.Headers.Add("Authorization", "A1203016"); if (param != null) { //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters"); //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas); PostData = Encoding.UTF8.GetBytes(param[0].ToString()); webRequest.ContentLength = PostData.Length; } if (reqMethod == RequestMethod.Post.ToString()) { Stream RequestStream = webRequest.GetRequestStream(); if (PostData != null) { RequestStream.Write(PostData, 0, PostData.Length); } RequestStream.Close(); RequestStream.Dispose(); } webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream ResponseStrem = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(ResponseStrem); string ValueString = reader.ReadToEnd(); jobj = JObject.Parse(ValueString); //jsonobj = JArray.Parse(ValueString); ResponseStrem.Dispose(); webResponse.Close(); } catch (ThreadInterruptedException) { string messge = string.Format("调用接口超时,线程被中断,Url=[{0}]", url); //LogMessageHelper.RecordLogMessage(messge, threx); //Log4netHelper.Logger_Error.Error(messge); } catch (WebException) { //webResponse = (HttpWebResponse)webex.Response; //StreamReader sr = new StreamReader(webResponse.GetResponseStream()); //string temp = sr.ReadToEnd(); string messge = string.Format("通信接口错误,Url={0}", url); //LogMessageHelper.RecordLogMessage(messge, webex); } catch (Exception) { string messge = string.Format("通信接口错误,Url={0}", url); //LogMessageHelper.RecordLogMessage(messge, ex); } finally { if (webResponse != null) { webResponse.Close(); webResponse = null; } if (webRequest != null) { webRequest.Abort(); webRequest = null; } } return jobj; } internal static JObject SendAsyncInfoToWebAPI(string url, string user_Id = null, string reqMethod = "Get", JArray param = null) { //JArray jsonobj =new JArray(); JObject jobj = null; HttpWebRequest webRequest = null; HttpWebResponse webResponse = null; try { webRequest = (HttpWebRequest)HttpWebRequest.Create(url); webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.Method = reqMethod; webRequest.AllowAutoRedirect = false; webRequest.Timeout = 5000; byte[] PostData = null; if (user_Id != null) webRequest.Headers.Add("Authorization", user_Id); //webRequest.Headers.Add("Authorization", "A1203016"); if (param != null) { //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters"); //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas); PostData = Encoding.UTF8.GetBytes(param[0].ToString()); webRequest.ContentLength = PostData.Length; } if (reqMethod == RequestMethod.Post.ToString()) { Stream RequestStream = webRequest.GetRequestStream(); if (PostData != null) { RequestStream.Write(PostData, 0, PostData.Length); } RequestStream.Close(); RequestStream.Dispose(); } //webResponse = (HttpWebResponse)webRequest.GetResponse(); webRequest.BeginGetResponse(AsyncCallbackResponse, webRequest); //Stream ResponseStrem = webResponse.GetResponseStream(); //StreamReader reader = new StreamReader(ResponseStrem); //string ValueString = reader.ReadToEnd(); //jobj = JObject.Parse(ValueString); //jsonobj = JArray.Parse(ValueString); //ResponseStrem.Dispose(); webResponse.Close(); } catch (WebException webex) { webResponse = (HttpWebResponse)webex.Response; StreamReader sr = new StreamReader(webResponse.GetResponseStream()); string temp = sr.ReadToEnd(); string messge = string.Format("通信接口错误,Url={0}", url); } catch (Exception) { string messge = string.Format("通信接口错误,Url={0}", url); } finally { if (webResponse != null) { webResponse.Close(); webResponse = null; } if (webRequest != null) { webRequest.Abort(); webRequest = null; } } return jobj; } internal static JArray SendInfoToWebAPIList(string url, string user_Id = null, string reqMethod = "Get", JArray param = null) { JArray jsonobj = new JArray(); //JObject jobj = null; HttpWebRequest webRequest = null; HttpWebResponse webResponse = null; try { webRequest = (HttpWebRequest)HttpWebRequest.Create(url); //webRequest.ContentType = "application/x-www-form-urlencoded"; webRequest.ContentType = "application/json"; //webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727) "; webRequest.Method = reqMethod; webRequest.AllowAutoRedirect = false; webRequest.Timeout = 50000; byte[] PostData = null; if (user_Id != null) webRequest.Headers.Add("Authorization", user_Id); //webRequest.Headers.Add("Authorization", "A1203016"); if (param != null) { //string paraUrlCoded = System.Web.HttpUtility.UrlEncode("paramaters"); //paraUrlCoded += "=" + System.Web.HttpUtility.UrlEncode(jsonParas); PostData = Encoding.UTF8.GetBytes(param[0].ToString()); webRequest.ContentLength = PostData.Length; } if (reqMethod == RequestMethod.Post.ToString()) { Stream RequestStream = webRequest.GetRequestStream(); if (PostData != null) { RequestStream.Write(PostData, 0, PostData.Length); } RequestStream.Close(); RequestStream.Dispose(); } webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream ResponseStrem = webResponse.GetResponseStream(); StreamReader reader = new StreamReader(ResponseStrem); string ValueString = reader.ReadToEnd(); //jobj = JObject.Parse(ValueString); jsonobj = JArray.Parse(ValueString); ResponseStrem.Dispose(); webResponse.Close(); } catch (WebException) { //webResponse = (HttpWebResponse)webex.Response; //StreamReader sr = new StreamReader(webResponse.GetResponseStream()); //string temp = sr.ReadToEnd(); string messge = string.Format("通信接口错误,Url={0}", url); } catch (Exception) { string messge = string.Format("通信接口错误,Url={0}", url); } finally { if (webResponse != null) { webResponse.Close(); webResponse = null; } if (webRequest != null) { webRequest.Abort(); webRequest = null; } } return jsonobj; } private static void AsyncCallbackResponse(IAsyncResult ar) { HttpWebRequest webrequest = ar.AsyncState as HttpWebRequest; var webresponse = webrequest.EndGetResponse(ar) as HttpWebResponse; Stream ResponseStrem = webresponse.GetResponseStream(); using (StreamReader reader = new StreamReader(ResponseStrem)) { string ValueString = reader.ReadToEnd(); } } /// /// 生成Json格式 /// public static string GetJson(object obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } /// /// 生成Json格式 /// public static string GetJson_2(T t) { DataContractJsonSerializer json = new DataContractJsonSerializer(typeof(T)); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, t); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } /// /// Json转Model /// public static T ParseFromJson(string szJson) { T obj = Activator.CreateInstance(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } /// /// Json转List /// public static List ParseToListFromJson(JArray ja) { var result = new List(); foreach (var item in ja) { result.Add(ParseFromJson(item.ToString())); } return result; } } }