123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.IO.Compression;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
- namespace efunbox_xyyf_windows.util
- {
- public class HttpUtil
- {
- public static HttpResult HttpRequest(HttpItem httpItem)
- {
- HttpResult result = new HttpResult();
- try
- {
- HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(httpItem.Url);
- httpWebRequest.Method = httpItem.Method.ToString();
- httpWebRequest.Headers = httpItem.Header;
- httpWebRequest.ContentType = HttpContentType.APPLICATION_JSON;
- httpWebRequest.Timeout = httpItem.TimeOut;
- if (httpItem.Method == RequestMethod.POST && (httpItem.RequestValue != null))
- {
- httpWebRequest.ContentLength = httpItem.RequestValue.Length;
- using (Stream requestStream = httpWebRequest.GetRequestStream())
- {
- requestStream.Write(httpItem.RequestValue, 0, httpItem.RequestValue.Length);
- }
- }
- try
- {
- //正常情况获取web服务器返回数据
- var httpWebResponse = (System.Net.HttpWebResponse)httpWebRequest.GetResponse();
- using (Stream responseStream = httpWebResponse.GetResponseStream())
- {
- MemoryStream memoryStream = new MemoryStream();
- responseStream.CopyTo(memoryStream);
- result.HttpByteData = memoryStream.ToArray();
- memoryStream.Seek(0, SeekOrigin.Begin);
- result.HttpStringData = (httpWebResponse.ContentEncoding != null && httpWebResponse.ContentEncoding.Equals("gzip", StringComparison.InvariantCultureIgnoreCase)) ? memoryStream.ReadGzipText(httpItem.Encoding) : memoryStream.ReadText(httpItem.Encoding);
- }
- }
- catch (System.Net.WebException ex)
- {
- Console.Write(ex.Message);//远程服务器返回错误: (400) 错误的请求。
- var strResponse = GetResponseAsString((System.Net.HttpWebResponse)ex.Response, Encoding.UTF8);//这样获取web服务器返回数据
- result.HttpStringData = strResponse;
- }
- return result;
- }
- catch (Exception ex)
- {
- result.Status = false;
- result.Msg = ex.Message;
- return result;
- }
- }
- private static string GetResponseAsString(HttpWebResponse res, Encoding encoding)
- {
- try
- {
- StreamReader sr = new StreamReader(res.GetResponseStream(), encoding);
- return sr.ReadToEnd();
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return "GetResponseAsString catch";
- }
- }
- }
- public class HttpItem
- {
- /// <summary>
- /// Url地址
- /// </summary>
- private string url;
- public string Url
- {
- get
- {
- if (!url.ToLower().StartsWith("http"))
- {
- url = "http://" + url;
- }
- return url;
- }
- set { url = value; }
- }
- /// <summary>
- /// Method
- /// </summary>
- public RequestMethod Method { get; set; } = RequestMethod.POST;
- /// <summary>
- /// 超时时间
- /// </summary>
- public int TimeOut { get; set; } = 1000 * 60;
- /// <summary>
- /// 接收的ContentType
- /// </summary>
- public string ContentType { get; set; } = HttpContentType.APPLICATION_JSON;
- /// <summary>
- /// 发送的ContentType
- /// </summary>
- public string HeaderContentType { get; set; } = HttpContentType.APPLICATION_JSON;
- /// <summary>
- ///
- /// </summary>
- public string UserAgent { get; set; }
- /// <summary>
- /// 编码
- /// </summary>
- public Encoding Encoding { get; set; } = Encoding.UTF8;
- /// <summary>
- /// 发送的数据类型
- /// </summary>
- public RequesDataType RequestDataType { get; set; } = RequesDataType.Text;
- /// <summary>
- /// 发送的数据
- /// </summary>
- public object RequestData { get; set; }
- /// <summary>
- /// 根据数据类型转换数据
- /// </summary>
- public byte[] RequestValue
- {
- get
- {
- byte[] bytes = null;
- if (RequestData != null)
- {
- switch (RequestDataType)
- {
- case RequesDataType.Text:
- bytes = Encoding.GetBytes(RequestData.ToString());
- //bytes = Encoding.UTF8.GetBytes(RequestData.ToString());
- break;
- case RequesDataType.StringText:
- bytes = Encoding.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(RequestData));
- break;
- case RequesDataType.Byte:
- bytes = RequestData as byte[];
- break;
- }
- }
- return bytes;
- }
- }
- private WebHeaderCollection _header;
- /// <summary>
- /// 设置Header
- /// </summary>
- public WebHeaderCollection Header
- {
- get
- {
- if (_header == null)
- {
- _header = new WebHeaderCollection();
- }
- //使用下面语句会出现异常 :error:必须使用适当的属性或方法修改“Content-Type”标头。
- //_header.Add(HttpResponseHeader.ContentType, HeaderContentType);
- return _header;
- }
- set { _header = value; }
- }
- public HttpItem(string url, RequesDataType requestDataType = RequesDataType.Text, object requestData = null)
- {
- Url = url;
- RequestDataType = requestDataType;
- RequestData = requestData;
- }
- }
- public class HttpResult
- {
- public bool Status { get; set; } = true;
- public string Msg { get; set; } = "Success";
- public string HttpStringData { get; set; }
- public byte[] HttpByteData { get; set; }
- }
- public enum RequestMethod
- {
- GET, POST
- }
- public enum RequesDataType
- {
- Text,
- // 如果WebApi设置接收类型为[FromBody]String,需将数据先转义为String
- // 如:SendData:"data", 转义:"\"data\""
- StringText,
- Byte
- }
- }
- /// <summary>
- /// Stream扩展类
- /// </summary>
- public static class StreamEx
- {
- /// <summary>
- /// 流转字符串
- /// </summary>
- /// <param name="stream"></param>
- /// <param name="encoding"></param>
- /// <returns></returns>
- public static string ReadText(this Stream stream, Encoding encoding)
- {
- string text = string.Empty;
- using (StreamReader streamReader = new StreamReader(stream, encoding))
- {
- text = streamReader.ReadToEnd();
- }
- return text;
- }
- /// <summary>
- /// 流转Gzip压缩字符串
- /// </summary>
- /// <param name="stream"></param>
- /// <param name="encoding"></param>
- /// <returns></returns>
- public static string ReadGzipText(this Stream stream, Encoding encoding)
- {
- string text = string.Empty;
- using (GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress))
- {
- using (StreamReader reader = new StreamReader(gZipStream, encoding))
- {
- text = reader.ReadToEnd();
- }
- }
- return text;
- }
- }
- /// <summary>
- /// HTTP 内容类型(Content-Type)
- /// </summary>
- public class HttpContentType
- {
- /// <summary>
- /// 资源类型:普通文本
- /// </summary>
- public const string TEXT_PLAIN = "text/plain";
- /// <summary>
- /// 资源类型:JSON字符串
- /// </summary>
- public const string APPLICATION_JSON = "application/json";
- /// <summary>
- /// 资源类型:未知类型(数据流)
- /// </summary>
- public const string APPLICATION_OCTET_STREAM = "application/octet-stream";
- /// <summary>
- /// 资源类型:表单数据(键值对)
- /// </summary>
- public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
- /// <summary>
- /// 资源类型:表单数据(键值对)。编码方式为 gb2312
- /// </summary>
- public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";
- /// <summary>
- /// 资源类型:表单数据(键值对)。编码方式为 utf-8
- /// </summary>
- public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";
- /// <summary>
- /// 资源类型:多分部数据
- /// </summary>
- public const string MULTIPART_FORM_DATA = "multipart/form-data";
- }
|