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
{
///
/// Url地址
///
private string url;
public string Url
{
get
{
if (!url.ToLower().StartsWith("http"))
{
url = "http://" + url;
}
return url;
}
set { url = value; }
}
///
/// Method
///
public RequestMethod Method { get; set; } = RequestMethod.POST;
///
/// 超时时间
///
public int TimeOut { get; set; } = 1000 * 60;
///
/// 接收的ContentType
///
public string ContentType { get; set; } = HttpContentType.APPLICATION_JSON;
///
/// 发送的ContentType
///
public string HeaderContentType { get; set; } = HttpContentType.APPLICATION_JSON;
///
///
///
public string UserAgent { get; set; }
///
/// 编码
///
public Encoding Encoding { get; set; } = Encoding.UTF8;
///
/// 发送的数据类型
///
public RequesDataType RequestDataType { get; set; } = RequesDataType.Text;
///
/// 发送的数据
///
public object RequestData { get; set; }
///
/// 根据数据类型转换数据
///
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;
///
/// 设置Header
///
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
}
}
///
/// Stream扩展类
///
public static class StreamEx
{
///
/// 流转字符串
///
///
///
///
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;
}
///
/// 流转Gzip压缩字符串
///
///
///
///
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;
}
}
///
/// HTTP 内容类型(Content-Type)
///
public class HttpContentType
{
///
/// 资源类型:普通文本
///
public const string TEXT_PLAIN = "text/plain";
///
/// 资源类型:JSON字符串
///
public const string APPLICATION_JSON = "application/json";
///
/// 资源类型:未知类型(数据流)
///
public const string APPLICATION_OCTET_STREAM = "application/octet-stream";
///
/// 资源类型:表单数据(键值对)
///
public const string WWW_FORM_URLENCODED = "application/x-www-form-urlencoded";
///
/// 资源类型:表单数据(键值对)。编码方式为 gb2312
///
public const string WWW_FORM_URLENCODED_GB2312 = "application/x-www-form-urlencoded;charset=gb2312";
///
/// 资源类型:表单数据(键值对)。编码方式为 utf-8
///
public const string WWW_FORM_URLENCODED_UTF8 = "application/x-www-form-urlencoded;charset=utf-8";
///
/// 资源类型:多分部数据
///
public const string MULTIPART_FORM_DATA = "multipart/form-data";
}