/// <summary>
/// jwt 验证接口
/// </summary>
/// <param name="url"></param>
/// <param name="data"></param>
/// <returns></returns>
public static string PostBearerAsync(string Url, string token, string data)
{
string retString = string.Empty;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Headers.Add("Authorization", "Bearer " + token);
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(data);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
retString = reader.ReadToEnd();
}
catch (Exception ex)
{
retString = ex.Message.ToString();
}
return retString;
}
public static async Task<string> PostAsync(string serviceAddress, string strContent, string ContentType, string m_Username, string m_Password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceAddress);
request.Method = "POST";
if (string.IsNullOrEmpty(ContentType))
{
request.ContentType = "application/json";
}
else
{
request.ContentType = ContentType;
}
string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
string base64Credentials = Convert.ToBase64String(byteCredentials);
request.Headers.Add("Authorization", "Basic " + base64Credentials);
using (StreamWriter dataStream = new StreamWriter(request.GetRequestStream()))
{
dataStream.Write(strContent);
dataStream.Close();
}
HttpWebResponse response = (HttpWebResponse)await request.GetResponseAsync();
string encoding = response.ContentEncoding;
if (encoding == null || encoding.Length < 1)
{
encoding = "UTF-8"; //默认编码
}
StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encoding));
string retString = reader.ReadToEnd();
return retString;
//解析josn
//JObject jo = JObject.Parse(retString);
//Response.Write(jo["message"]["mmmm"].ToString());
}
标签:dataStream,string,encoding,jwt,request,retString,httppost,basic,response
From: https://www.cnblogs.com/yunnn/p/16821963.html