|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212 |
- 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
- {
- /// <summary>
- /// HttpHelper
- /// 创建人:赵耀
- /// </summary>
- 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<string, string> param)
- {
- var paramBuilder = new List<string>();
- 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;
- }
- /// <summary>
- /// Post Http请求
- /// </summary>
- /// <param name="url">请求地址</param>
- /// <param name="postData">传输数据</param>
- /// <param name="timeout">超时时间</param>
- /// <param name="contentType">媒体格式</param>
- /// <param name="encode">编码</param>
- /// <returns>泛型集合</returns>
- public static T PostAndRespSignle<T>(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<T>(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();
- }
-
- }
- }
|