using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json;
using NLog;
namespace Helper
{
public class HttpHelper
{
private static string m_TokenURL = ConfigurationManager.AppSettings["HW_TOKEN_URL"];
private static string m_TokenKey = ConfigurationManager.AppSettings["APP_KEY"];
private static string m_TokenSecury = ConfigurationManager.AppSettings["APP_SECURY"];
private static volatile Token m_TokenMap = null;
private static DateTime m_ExpiresDate ;
private static HttpHelper m_TokenUtil;
private static Object o = new Object();
public bool is_expires = true;
public static HttpHelper GetInstance()
{
lock (o)
{
if (m_TokenUtil == null)
{
m_TokenUtil = new HttpHelper();
}
}
return m_TokenUtil;
}
public string GetDynamicToken()
{
System.DateTime currentTime = DateTime.Now;
if (m_ExpiresDate <= currentTime)
{
Token mapToken = GetAccessToken();
string strExpires = mapToken.expires_in;
int lExpires = Int32.Parse(strExpires);
bool min = lExpires <= 5;
while (min)
{// 小于5秒的token重新获取,服务端被设置为5秒获取新token
mapToken = GetAccessToken();
strExpires = mapToken.expires_in;
lExpires = Int32.Parse(strExpires);
min = lExpires > 5;
}
// 设置时间轴
System.DateTime endTime = DateTime.Now;
m_ExpiresDate = endTime.AddSeconds(lExpires);
// 缓存token
m_TokenMap = mapToken;
}
return m_TokenMap.access_token;
}
// 添加https
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
// end添加https
public static Token GetAccessToken()
{
string result = GetRequestToken();
m_TokenMap = JsonConvert.DeserializeObject<Token>(result);
//MessageBox.Show("成功获取动态令牌信息Token:" + m_TokenMap.access_token);
return m_TokenMap;
}
public static string GetRequestToken()
{
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream requestStream = null;
Stream responseStream = null;
try
{
request = (HttpWebRequest)WebRequest.Create(m_TokenURL);
// 添加https
if (m_TokenURL.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
request.UserAgent = DefaultUserAgent;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/x-www-form-urlencoded";
string authorization = "Basic " + Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(m_TokenKey + ":" + m_TokenSecury)).Trim();
request.Headers.Add("Authorization", authorization);
string postData = "grant_type=client_credentials";
if (!string.IsNullOrEmpty(postData))//如果传送的数据不为空,并且方法是post
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("UTF-8").GetBytes(postData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
request.ContentLength = bytes.Length;
using (requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
using (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 (responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
return responseValue;
}
}
catch (Exception e)
{
//MessageBox.Show("sendRequest:" + e.Message);
throw e;
}
finally
{
if (requestStream != null)
requestStream.Close();
if (responseStream != null)
responseStream.Close();
if (response != null)
{
response.Close();
response.Dispose();
}
if (request != null)
request.Abort();
}
}
public static string GetDataFromAPI(ILogger logger,string apiURL, string postData)
{
logger.Debug("API_URL:" + apiURL + ",PostData:" + postData);
HttpWebRequest request = null;
HttpWebResponse response = null;
Stream requestStream = null;
Stream responseStream = null;
try
{
request = (HttpWebRequest)WebRequest.Create(apiURL);
// 添加https
if (apiURL.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
request.UserAgent = DefaultUserAgent;
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
}
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/json;charset=UTF-8";
string authorization = "Bearer " + HttpHelper.GetInstance().GetDynamicToken();
request.Headers.Add("Authorization", authorization);
if (!string.IsNullOrEmpty(postData))//如果传送的数据不为空,并且方法是post
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("UTF-8").GetBytes(postData);//编码方式按自己需求进行更改,我在项目中使用的是UTF-8
request.ContentLength = bytes.Length;
using (requestStream = request.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}
}
using (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 (responseStream = response.GetResponseStream())
{
if (responseStream != null)
using (var reader = new StreamReader(responseStream))
{
responseValue = reader.ReadToEnd();
}
}
logger.Debug("ResponseValue:" + responseValue);
return responseValue;
}
}
catch (Exception e)
{
//MessageBox.Show("sendRequest:" + e.Message);
throw e;
}
finally
{
if (requestStream != null)
requestStream.Close();
if (responseStream != null)
responseStream.Close();
if (response != null)
{
response.Close();
response.Dispose();
}
if (request != null)
request.Abort();
}
}
}
}
Http Helper
最新推荐文章于 2024-01-02 10:32:36 发布