using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
namespace Common.system
{
///
/// HttpHelper
/// 创建人:赵耀
///
public class HttpHelper
{
public static void init_Request(ref System.Net.HttpWebRequest request)
{
request.Accept = "text/json,*/*;q=0.5";
request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
request.Timeout = 8000;
}
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
public static System.Net.HttpWebRequest GetHttpWebRequest(string url)
{
HttpWebRequest request = null;
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
return request;
}
public static WebResponse Download(string downloadUrl, long from, long to, string method)
{
for (int i = 0; i < 10; i++)
{
try
{
var request = HttpHelper.GetHttpWebRequest(downloadUrl);
HttpHelper.init_Request(ref request);
request.Accept = "text/json,*/*;q=0.5";
request.AddRange(from, to);
request.Headers.Add("Accept-Charset", "utf-8;q=0.7,*;q=0.7");
request.Headers.Add("Accept-Encoding", "gzip, deflate, x-gzip, identity; q=0.9");
request.AutomaticDecompression = System.Net.DecompressionMethods.GZip;
request.Timeout = 120000;
request.Method = method;
request.KeepAlive = false;
request.ContentType = "application/json; charset=utf-8";
return request.GetResponse();
}
catch (Exception)
{
Thread.Sleep(100);
}
}
throw new Exception("已断开网络!请检查网络连接后重试下载!");
}
public static string Get(string url, IDictionary param)
{
var paramBuilder = new List();
foreach (var item in param)
{
paramBuilder.Add(string.Format("{0}={1}", item.Key, item.Value));
}
url = string.Format("{0}?{1}", url.TrimEnd('?'), string.Join(",", paramBuilder.ToArray()));
return Get(url);
}
public static string Get(string url)
{
try
{
var request = GetHttpWebRequest(url);
if (request != null)
{
string retval = null;
init_Request(ref request);
using (var Response = request.GetResponse())
{
using (var reader = new System.IO.StreamReader(Response.GetResponseStream(), System.Text.Encoding.UTF8))
{
retval = reader.ReadToEnd();
}
}
return retval;
}
}
catch
{
}
return null;
}
public static string Post(string url, string data)
{
try
{
var request = GetHttpWebRequest(url);
if (request != null)
{
string retval = null;
init_Request(ref request);
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
request.ContentType = "application/json; charset=utf-8";
request.Timeout = 800;
var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(data);
request.ContentLength = bytes.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(bytes, 0, bytes.Length);
}
using (var response = request.GetResponse())
{
using (var reader = new System.IO.StreamReader(response.GetResponseStream()))
{
retval = reader.ReadToEnd();
}
}
return retval;
}
}
catch
{
}
return null;
}
///
/// Post Http请求
///
/// 请求地址
/// 传输数据
/// 超时时间
/// 媒体格式
/// 编码
/// 泛型集合
public static T PostAndRespSignle(string url, int timeout = 5000, string postData = "", string contentType = "application/json;", string encode = "UTF-8") where T : class
{
if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
{
// webRequest.Headers.Add("Authorization", "Bearer " + "SportApiAuthData");
HttpWebResponse webResponse = null;
Stream responseStream = null;
Stream requestStream = null;
StreamReader streamReader = null;
try
{
string respstr = GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postData, contentType);
return JsonHelper.JsonToObj(respstr);
}
catch (Exception)
{
}
finally
{
if (responseStream != null)
{
responseStream.Dispose();
}
if (webResponse != null)
{
webResponse.Close();
}
if (requestStream != null)
{
requestStream.Dispose();
}
if (streamReader != null)
{
streamReader.Dispose();
}
}
}
return default(T);
}
private static string GetStreamReader(string url, Stream responseStream, Stream requestStream, StreamReader streamReader, WebResponse webResponse, int timeout, string encode, string postData, string contentType)
{
byte[] data = Encoding.GetEncoding(encode).GetBytes(postData);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Method = "POST";
webRequest.ContentType = contentType + ";" + encode;
webRequest.ContentLength = data.Length;
webRequest.Timeout = timeout;
requestStream = webRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
webResponse = (HttpWebResponse)webRequest.GetResponse();
responseStream = webResponse.GetResponseStream();
if (responseStream == null) { return ""; }
streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encode));
return streamReader.ReadToEnd();
}
}
}