|
|
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Text; using System.Threading.Tasks;
namespace ICSSoft.Common { public class HTTPHelper { private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public static string HttpPost(string apiName, string url, string body) { try { //log.Debug(url + Environment.NewLine + body);
Encoding encoding = Encoding.UTF8; System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(url); request.Method = "POST"; request.Accept = "application/json, text/javascript, */*"; //"text/html, application/xhtml+xml, */*";
request.ContentType = "application/json; charset=utf-8"; // request.ContentType = "text/html, application/xhtml+xml";
byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } catch (System.Net.WebException ex) { log.Error(ex.ToString() + Environment.NewLine + url + Environment.NewLine + body); throw new Exception(apiName + "调用失败," + ex.Message); } }
public static string HttpPost(string url, string body) { try { Encoding encoding = Encoding.UTF8; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.Accept = "text/html, application/xhtml+xml, */*"; request.ContentLength = 110; request.ContentType = "application/json";
byte[] buffer = encoding.GetBytes(body); request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); log.Error(url + body); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { return reader.ReadToEnd(); } } catch (WebException ex) { var res = (HttpWebResponse)ex.Response; StringBuilder sb = new StringBuilder(); StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8); sb.Append(sr.ReadToEnd()); //string ssb = sb.ToString();
//throw new Exception(sb.ToString());
return ""; } }
/// <summary>
/// 通过web api获取数据的方法
/// </summary>
/// <param name="url">api的url</param>
/// <param name="method">请求类型,默认是get</param>
/// <param name="postData">post请求所携带的数据</param>
/// <returns></returns>
public static string RequestData(string url, string method, string postData) { try { log.Error(postData); method = method.ToUpper(); //设置安全通信协议 我方公司服务器有些强制使用tls1.2的安全通信协议,所以至少包含SecurityProtocolType.Tls12 如果沒有SecurityProtocolType.Tls12设置会报错:HttpWebRequest底层连接已关闭:传送时发生意外错误
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
//创建请求实例
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
//设置请求类型
request.Method = method; //设置请求消息主体的编码方法
request.ContentType = "application/json";
//POST方式處理
if (method == "POST") { //用UTF8字符集对post请求携带的数据进行编码,可防止中文乱码
byte[] byteArray = Encoding.UTF8.GetBytes(postData); //指定客户端post请求携带的数据的长度
request.ContentLength = byteArray.Length;
//创建一个tream,用于写入post请求所携带的数据(该数据写入了请求体)
Stream stream = request.GetRequestStream(); stream.Write(byteArray, 0, byteArray.Length); stream.Close(); }
//获取请求的响应实例
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); //获取读取流实体,用来以UTF8字符集读取响应流中的数据
StreamReader myStreamReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //进行数据读取
string retString = myStreamReader.ReadToEnd(); myStreamReader.Close(); return retString; } catch (Exception ex) { //拋出異常
throw ex; } }
public static string WorkDayPostData(string URL, string JsonData, string ContentType) { string str = string.Empty; try { WebRequest request = WebRequest.Create(URL); request.Method = "POST"; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(JsonData); request.ContentType = ContentType; request.ContentLength = bytes.Length; using (Stream postStream = request.GetRequestStream()) { postStream.Write(bytes, 0, bytes.Length); } request.Credentials = CredentialCache.DefaultCredentials; WebResponse response = null; try { response = request.GetResponse(); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) response = (WebResponse)ex.Response; } if (response != null) { using (StreamReader st = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8)) { str = System.Web.HttpUtility.UrlDecode(st.ReadToEnd()); } } } catch (Exception ex) { str = ex.Message; } return str;
}
public static void CreateObject(string URL, string DATA) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = DATA.Length; StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), System.Text.Encoding.ASCII); requestWriter.Write(DATA); requestWriter.Close();
try { WebResponse webResponse = request.GetResponse(); Stream webStream = webResponse.GetResponseStream(); StreamReader responseReader = new StreamReader(webStream); string response = responseReader.ReadToEnd(); Console.Out.WriteLine(response); responseReader.Close(); } catch (Exception e) { Console.Out.WriteLine("-----------------"); Console.Out.WriteLine(e.Message); }
}
public static string Post(string posturl, string jsonstr) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(posturl);
request.Method = "POST"; request.ContentType = "application/x-www-form-urlencoded";
//json字符串转为字节数组
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(jsonstr);
//设置请求的ContentLength
request.ContentLength = bytes.Length;
//发送请求,获得请求流
Stream stream; try { //获取用于写入请求数据的Stream对象
stream = request.GetRequestStream(); } catch (Exception ex) { stream = null; Console.WriteLine(ex.Message); } //把数据写入流
stream.Write(bytes, 0, bytes.Length);
stream.Close();
HttpWebResponse response; try { //获得响应流
response = (HttpWebResponse)request.GetResponse(); } catch (WebException ex) { response = ex.Response as HttpWebResponse; }
Stream s = response.GetResponseStream();
StreamReader sr = new StreamReader(s, Encoding.UTF8);
string strVal = sr.ReadToEnd().Trim(); sr.Close();
s.Close();
return strVal; }
/// <summary>
/// HTTP访问method 常用的几样
/// </summary>
public enum HttpVerb { /// <summary>
/// get:获取
/// </summary>
GET, /// <summary>
/// post:修改
/// </summary>
POST, /// <summary>
/// put:写入
/// </summary>
PUT, /// <summary>
/// delete:删除
/// </summary>
DELETE } /// <summary>
/// HTTP访问格式类型,根据Postman整理
/// </summary>
public enum HttpContentType { /// <summary>
/// text/plain
/// </summary>
Text, /// <summary>
/// application/json
/// </summary>
JSON, /// <summary>
/// application/xml
/// </summary>
XML, /// <summary>
/// text/xml
/// </summary>
TextXML, /// <summary>
/// text/html
/// </summary>
HTML, /// <summary>
/// application/javascript
/// </summary>
Javascript } /// <summary>
/// Rest方式访问方法,ContentType为application/json
/// </summary>
public class RestHelper { /// <summary>
/// 请求的url地址
/// </summary>
public string EndPoint { get; set; } /// <summary>
/// 请求的方法,默认 GET
/// </summary>
public HttpVerb Method { get; set; } /// <summary>
/// 格式类型:默认application/json
/// </summary>
public HttpContentType ContentType { get; set; } /// <summary>
/// 传送的数据,如json字符串
/// </summary>
public string PostData { get; set; } /// <summary>
/// 编码规范,默认 UTF8
/// </summary>
public Encoding HttpEncoding { get; set; } /// <summary>
/// 构造函数
/// </summary>
public RestHelper(HttpContentType contentType = HttpContentType.JSON) { EndPoint = ""; Method = HttpVerb.GET; ContentType = contentType; PostData = ""; HttpEncoding = Encoding.UTF8; } /// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = HttpVerb.GET; ContentType = contentType; PostData = ""; HttpEncoding = Encoding.UTF8; } /// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, HttpVerb method, HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = ""; HttpEncoding = Encoding.UTF8; }
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, HttpVerb method, string postData, HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; HttpEncoding = Encoding.UTF8; }
/// <summary>
/// 构造函数
/// </summary>
public RestHelper(string endpoint, Encoding encoding, HttpVerb method = HttpVerb.GET, string postData = "", HttpContentType contentType = HttpContentType.JSON) { EndPoint = endpoint; Method = method; ContentType = contentType; PostData = postData; HttpEncoding = encoding; }
/// <summary>
/// 直接访问
/// </summary>
/// <returns></returns>
public string MakeRequest() { return MakeRequest(""); }
/// <summary>
/// 带参数访问,如 MakeRequest("?param=0")
/// </summary>
/// <param name="parameters"></param>
/// <returns></returns>
public string MakeRequest(string parameters) { try { var request = (HttpWebRequest)WebRequest.Create(EndPoint + parameters);
request.Method = Method.ToString(); request.ContentLength = 0; request.ContentType = GetContentType(ContentType);
//如果传送的数据不为空,并且方法是post或put
if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT)) { var bytes = HttpEncoding.GetBytes(PostData);//编码方式,默认UTF-8
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream()) { writeStream.Write(bytes, 0, bytes.Length); } } using (var response = (HttpWebResponse)request.GetResponse()) { var responseValue = string.Empty;
if (response.StatusCode != HttpStatusCode.OK) { var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode); throw new ApplicationException(message); }
// grab the response
using (var responseStream = response.GetResponseStream()) { if (responseStream != null) { using (var reader = new StreamReader(responseStream)) { responseValue = reader.ReadToEnd(); } } } return responseValue; }
} catch (Exception e) { throw new Exception(e.Message); } }
/// <summary>
/// 将content type转成字符串描述
/// </summary>
/// <param name="contentType"></param>
/// <returns></returns>
private string GetContentType(HttpContentType contentType) { switch (contentType) { case HttpContentType.Text: return "text/plain"; case HttpContentType.JSON: return "application/json"; case HttpContentType.XML: return "application/xml"; case HttpContentType.TextXML: return "text/xml"; case HttpContentType.HTML: return "text/html"; case HttpContentType.Javascript: return "application/javascript"; default: return ""; } }
}
} }
|