C# http请求工具类
/// <summary>
/// Http请求操作类之HttpWebRequest
/// </summary>
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 /// <summary>
/// Post
/// </summary>
/// <param name="url"></param>
/// <param name="msg"></param>
/// <returns></returns>
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;
} /// <summary>
/// Get
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
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;
} /// <summary>
/// Put
/// </summary>
/// <param name="data"></param>
/// <param name="uri"></param>
/// <returns></returns>
public string HTTPJsonDelete(string url, string data)
{
return CommonHttpRequest(data, url, "DELETE");
} /// <summary>
/// Put
/// </summary>
/// <param name="data"></param>
/// <param name="uri"></param>
/// <returns></returns>
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 /// <summary>
/// 获取客户端IP地址(无视代理)
/// </summary>
/// <returns>若失败则返回回送地址</returns>
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";
} } /// <summary>
/// 检查IP地址格式
/// </summary>
/// <param name="ip"></param>
/// <returns></returns>
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>(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;
}
} /// <summary>
/// Http请求操作类之WebClient
/// </summary> 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<string> onComplete, Action<Exception> 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请求工具类
C# http请求工具类的更多相关文章
- WebUtils-网络请求工具类
网络请求工具类,大幅代码借鉴aplipay. using System; using System.Collections.Generic; using System.IO; using System ...
- Http、Https请求工具类
最近在做微信开发,使用http调用第三方服务API,有些是需要https协议,通过资料和自己编码,写了个支持http和https的工具类,经验证可用,现贴出来保留,也供需要的人使用(有不足的地方,也请 ...
- 微信https请求工具类
工作中用到的微信https请求工具类. package com.gxgrh.wechat.tools; import com.gxgrh.wechat.wechatapi.service.System ...
- HTTP请求工具类
HTTP请求工具类,适用于微信服务器请求,可以自测 代码; /// <summary> /// HTTP请求工具类 /// </summary> public class Ht ...
- 实现一个简单的http请求工具类
OC自带的http请求用起来不直观,asihttprequest库又太大了,依赖也多,下面实现一个简单的http请求工具类 四个文件源码大致如下,还有优化空间 MYHttpRequest.h(类定义, ...
- 远程Get,Post请求工具类
1.远程请求工具类 import java.io.*; import java.net.URL; import java.net.URLConnection; import java.util.L ...
- C#实现的UDP收发请求工具类实例
本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...
- ajax请求工具类
ajax的get和post请求工具类: /** * 公共方法类 * * 使用 变量名=function()定义函数时,如果在变量名前加var,则这个变量变成局部变量 */var Common = ...
- 【原创】标准HTTP请求工具类
以下是个人在项目开发过程中,总结的Http请求工具类,主要包括四种: 1.处理http POST请求[XML格式.无解压]: 2.处理http GET请求[XML格式.无解压]: 3.处理http P ...
- 我的Android进阶之旅------>Android关于HttpsURLConnection一个忽略Https证书是否正确的Https请求工具类
下面是一个Android HttpsURLConnection忽略Https证书是否正确的Https请求工具类,不需要验证服务器端证书是否正确,也不需要验证服务器证书中的域名是否有效. (PS:建议下 ...
随机推荐
- Ajax中解析Json的两种方法
eval(); //此方法不推荐 JSON.parse(); //推荐方法 一.两种方法的区别 我们先初始化一个json格式的对象: var jsonDate = '{ "name" ...
- 四大伪类,css鼠标样式设置,reset操作,静止对文本操作
07.31自我总结 一.a标签的四大伪类 a:link{样式} 未访问时的状态(鼠标点击前显示的状态) a:hover{样式} 鼠标悬停时的状态 a:visited{样式} 已访问过的状态(鼠标点击后 ...
- 【es6】es6使用集锦
一.查找数组中是否包含某个元素 使用includes ,返回值为布尔值 arr.includes(searchElement, fromIndex): 解析:searchElement 查询元 ...
- YOLO---近段时间的练习目标
YOLO---近段时间的练习目标 yolo(darknet)官方主页:https://pjreddie.com/darknet/yolo/ 和在学校时用的不太一样了,有更新了- 还有一个常用版本: ...
- Java基础 String 裸暴力算法- 五个小练习
之间的博客,承上启下: Java基础 String/StringBuff 常用操作方法复习/内存分析 Java数组直接选择排序.sort()排序 Java基础 String 算法 - 五个练 ...
- 0010Springboot整合thymeleaf
1.pom.xml中添加thymeleaf的起步依赖 2.编写html文件并放在classpath:/templates/路径下 3.编写controller并返回字符串,会到classpath:/t ...
- django已经安装但是还是提示ModuleNotFoundError: No module named 'django'
首先查看自己django版本与python版本是否一致: 如果一致.可能是django安装的位置与python导包的位置不一致. 我将之前的python2.6升级到python3.6,结果pip in ...
- 数组排序方法(join()、reverse()、sort())
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 11、Spring Boot 2.x 集成 HBase
1.11 Spring Boot 2.x 集成 HBase 完整源码: Spring-Boot-Demos
- VSCode:配置自动修复eslint
{ //"tfvc.location": "C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Profess ...