博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# http请求工具类
阅读量:6079 次
发布时间:2019-06-20

本文共 8737 字,大约阅读时间需要 29 分钟。

///     /// Http请求操作类之HttpWebRequest    ///     public class HttpHelper    {        #region properties        private ILog _logger;        private readonly Encoding ENCODING = Encoding.UTF8;        #endregion        #region constructor        public HttpHelper()        {            this._logger = LogManager.GetLogger("HttpHelper");        }        #endregion        #region public methods        ///         /// Post        ///         ///         ///         /// 
public string HTTPJsonPost(string url, string msg) { string result = string.Empty; try { this._logger.InfoFormat("HTTPJsonPostUrl:{0}", url); this._logger.InfoFormat("HTTPJsonPostMsg:{0}", msg); result = CommonHttpRequest(msg, url, "POST"); //if (!result.Contains("\"Code\":200")) //{ // throw new Exception(result); //} } catch (WebException ex) { if (ex.Response != null) { HttpWebResponse response = (HttpWebResponse)ex.Response; Console.WriteLine("Error code: {0}", response.StatusCode); switch (response.StatusCode) { case HttpStatusCode.BadRequest: case HttpStatusCode.Forbidden: case HttpStatusCode.InternalServerError: { using (Stream data = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(data)) { string text = reader.ReadToEnd(); throw new Exception(text); } } } break; } } this._logger.ErrorFormat("HTTPJsonPost异常:{0}", ex.Message); } catch (Exception ex) { this._logger.ErrorFormat("HTTPJsonPost异常:{0}", ex.Message); throw new Exception(ex.Message); } return result; } /// /// Get /// /// ///
public string HTTPJsonGet(string url) { string result = string.Empty; try { this._logger.InfoFormat("HTTPJsonPostUrl:{0}", url); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.ContentType = "application/json"; request.Method = "GET"; HttpWebResponse resp = request.GetResponse() as HttpWebResponse; System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream(), this.ENCODING); result = reader.ReadToEnd(); } catch (Exception ex) { this._logger.ErrorFormat("HTTPJsonGet异常:{0}", ex.Message); } return result; } /// /// Put /// /// /// ///
public string HTTPJsonDelete(string url, string data) { return CommonHttpRequest(data, url, "DELETE"); } /// /// Put /// /// /// ///
public string HTTPJsonPut(string url, string data) { return CommonHttpRequest(data, url, "PUT"); } #endregion #region private public string CommonHttpRequest(string data, string uri, string type) { //Web访问对象,构造请求的url地址 string serviceUrl = uri; //构造http请求的对象 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(serviceUrl); myRequest.Timeout = 600000; //转成网络流 byte[] buf = this.ENCODING.GetBytes(data); //设置 myRequest.Method = type; myRequest.ContentLength = buf.LongLength; myRequest.ContentType = "application/json"; //将客户端IP加到头文件中 string sRealIp = GetHostAddress(); if (!string.IsNullOrEmpty(sRealIp)) { myRequest.Headers.Add("ClientIp", sRealIp); } using (Stream reqstream = myRequest.GetRequestStream()) { reqstream.Write(buf, 0, (int)buf.Length); } HttpWebResponse resp = myRequest.GetResponse() as HttpWebResponse; System.IO.StreamReader reader = new System.IO.StreamReader(resp.GetResponseStream(), this.ENCODING); string ReturnXml = reader.ReadToEnd(); reader.Close(); resp.Close(); return ReturnXml; } #endregion /// /// 获取客户端IP地址(无视代理) /// ///
若失败则返回回送地址
public static string GetHostAddress() { try { string userHostAddress = HttpContext.Current.Request.UserHostAddress; if (string.IsNullOrEmpty(userHostAddress)) { userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要) if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) { return userHostAddress; } return "127.0.0.1"; } catch { return "127.0.0.1"; } } /// /// 检查IP地址格式 /// /// ///
public static bool IsIP(string ip) { return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); } public static long ConvertDataTimeLong(DateTime dt) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); TimeSpan toNow = dt.Subtract(dtStart); long timeStamp = toNow.Ticks; timeStamp = long.Parse(timeStamp.ToString().Substring(0, timeStamp.ToString().Length - 4)); return timeStamp; } public static DateTime ConvertLongDateTime(long d) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(d + "0000"); TimeSpan toNow = new TimeSpan(lTime); DateTime dtResult = dtStart.Add(toNow); return dtResult; }   private string ConvertToJsonString
(T model) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T)); var stream = new MemoryStream(); serializer.WriteObject(stream, model); byte[] dataBytes = new byte[stream.Length]; stream.Position = 0; stream.Read(dataBytes, 0, (int)stream.Length); string dataString = Encoding.UTF8.GetString(dataBytes); return dataString; } } ///
/// Http请求操作类之WebClient /// public static class WebClientHelper { public static string Post(string url, string jsonData) { var client = new WebClient(); client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); client.Encoding = System.Text.Encoding.UTF8; byte[] data = Encoding.UTF8.GetBytes(jsonData); byte[] responseData = client.UploadData(new Uri(url), "POST", data); string response = Encoding.UTF8.GetString(responseData); return response; } public static void PostAsync(string url, string jsonData, Action
onComplete, Action
onError) { var client = new WebClient(); client.Headers.Add(HttpRequestHeader.ContentType, "application/json"); client.Encoding = System.Text.Encoding.UTF8; byte[] data = Encoding.UTF8.GetBytes(jsonData); client.UploadDataCompleted += (s, e) => { if (e.Error == null && e.Result != null) { string response = Encoding.UTF8.GetString(e.Result); onComplete(response); } else { onError(e.Error); } }; client.UploadDataAsync(new Uri(url), "POST", data); } } 
http请求工具类

 

转载于:https://www.cnblogs.com/fishyy/p/10243128.html

你可能感兴趣的文章
修改字符集
查看>>
HackTheGame 攻略 - 第四关
查看>>
js删除数组元素
查看>>
带空格文件名的处理(find xargs grep ..etc)
查看>>
华为Access、Hybrid和Trunk的区别和设置
查看>>
centos使用docker下安装mysql并配置、nginx
查看>>
关于HTML5的理解
查看>>
需要学的东西
查看>>
Internet Message Access Protocol --- IMAP协议
查看>>
Linux 获取文件夹下的所有文件
查看>>
对 Sea.js 进行配置(一) seajs.config
查看>>
第六周
查看>>
解释一下 P/NP/NP-Complete/NP-Hard 等问题
查看>>
javafx for android or ios ?
查看>>
微软职位内部推荐-Senior Software Engineer II-Sharepoint
查看>>
sql 字符串操作
查看>>
【转】Android布局优化之ViewStub
查看>>
网络安全管理技术作业-SNMP实验报告
查看>>
根据Uri获取文件的绝对路径
查看>>
Flutter 插件开发:以微信SDK为例
查看>>