NewGaoKaoApi/New_College.Common/Helper/CasdoorHttpHelper.cs

125 lines
4.0 KiB
C#

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Security.Policy;
using System.Text;
namespace New_College.Common
{
public class CasdoorHttpHelper
{
/// <summary>
/// post 统一请求接口
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="inter"></param>
/// <param name="content"></param>
/// <returns></returns>
public static T Http_Post<T>(string inter, Dictionary<string, string> headers, HttpContent content) where T : new()
{
var authinfo = new T();
try
{
string requestUri = string.Format("{0}/{1}", CasdoorConfig.Endpoint, inter);
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
//httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
if (headers != null && headers.Any())
{
httpClient.DefaultRequestHeaders.Add(headers.FirstOrDefault().Key, headers.FirstOrDefault().Value);
}
// var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(new CasdoorRefeshToken() { refresh_token = refresh_token, scope = "built-in", grant_type = "authorization_code", client_id = CasdoorConfig.ClientId, client_secret = CasdoorConfig.ClientSecret }), Encoding.UTF8, "application/json");
var responseStr = httpClient.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<T>(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
///泛型GET
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="inter"></param>
/// <param name="param"></param>
/// <returns></returns>
public static T Http_Get<T>(string inter, Dictionary<string, string> headers, Dictionary<string, string> dic) where T : new()
{
var authinfo = new T();
try
{
string result = "";
StringBuilder builder = new StringBuilder();
builder.Append(CasdoorConfig.Endpoint);
builder.Append(inter);
if (dic.Count > 0)
{
builder.Append("?");
int i = 0;
foreach (var item in dic)
{
if (i > 0)
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
}
var httpClientHandler = new HttpClientHandler
{
ServerCertificateCustomValidationCallback = (message, certificate2, arg3, arg4) => true,
};
using (HttpClient httpClient = new HttpClient(httpClientHandler))
{
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
if (headers.Any())
{
httpClient.DefaultRequestHeaders.Add(headers.FirstOrDefault().Key, headers.FirstOrDefault().Value);
}
var responseStr = httpClient.GetAsync(builder.ToString()).Result.Content.ReadAsStringAsync().Result;
var obj = JsonConvert.DeserializeObject<T>(responseStr);
return obj;
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}