JWT 请求API
/// <summary>
/// get请求
/// </summary>
/// <param name="url">请求地址</param>
/// <param name="timeout">超时时间,默认为60000毫秒(1分钟)</param>
/// <returns></returns>
public string GetHttpResponse(string url, int timeout = 3600000)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json;charset=UTF-8";
request.Accept = "text/plain";
request.UserAgent = null;
request.Timeout = timeout;
jwttoken = GetjwtToken(GetTokenUrl);
//往头部加入自定义验证信息
SetHeaderValue(request.Headers, "Authorization", "Bearer " + jwttoken);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close();
return retString;
}
/// <summary>
/// POST方式请求接口
/// </summary>
/// <param name="url"></param>
/// <param name="PostData"></param>
/// <param name="timeout"></param>
/// <returns></returns>
public string PostHttpGetTokenResponse(string url, Object PostData, int timeout = 60000)
{
HttpWebRequest request = null;
//HTTPSQ请求
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
request.Method = "POST";
request.ContentType = "application/json";
request.Accept = "text/plain";
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
request.Timeout = timeout;
//如果需要POST数据
string str = JsonConvert.SerializeObject(PostData);
byte[] data = Encoding.GetEncoding("utf-8").GetBytes(str);
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var resultStream = (request.GetResponse() as HttpWebResponse);
string result = "";
//获取响应内容
using (StreamReader reader = new StreamReader(resultStream.GetResponseStream(), Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
}
/// <summary>
/// 往头部加信息
/// </summary>
/// <param name="header">bearer</param>
/// <param name="name"></param>
/// <param name="value"></param>
public static void SetHeaderValue(WebHeaderCollection header, string name, string value)
{
var property = typeof(WebHeaderCollection).GetProperty("InnerCollection", BindingFlags.Instance | BindingFlags.NonPublic);
if (property != null)
{
var collection = property.GetValue(header, null) as NameValueCollection;
collection[name] = value;
}
}
/// <summary>
/// 访问获取token的地址
/// </summary>
/// <param name="gettokenurl"></param>
/// <returns>返回token</returns>
public string GetjwtToken(string gettokenurl)
{
object author = new { userName = UserName, password = PassWord };
var json = PostHttpGetTokenResponse(gettokenurl, author);
var jsonobj = JsonHelper.ToObject<RootJsonToken>(json);
return jsonobj.data.accessToken;
}