Post请求接口,参数以json方式,SHA256计算加密
/// <summary>
/// 单点登陆
/// </summary>
/// <param name="context"></param>
public void DDLogin(HttpContext context)
{
try
{
//APIKey
var apikey = ConfigurationManager.AppSettings["APIkey"];
//Secretkey
var secretkey = ConfigurationManager.AppSettings["Secretkey"];
//Uname
var uname = LoginMethod.MemberID;
//视频链接
var videoUrl = context.Request.Form["HtmlUrl"];
//生成随机数
Random randObj = new Random();
int value = randObj.Next(10000);
string salt = value.ToString("0000");
//SHA256计算加密生成签名
string data = secretkey + salt;
string signature = sha256(data);
Method.Wlog("随机数:"+salt+" "+"签名signature:" + signature);
string jsonParam = "{ \"apikey\":\"" + apikey + "\",\"salt\":\"" + salt + "\",\"signature\":\"" + signature + "\",\"uname\":\"" + uname + "\"}";
Method.Wlog("单点登陆Json参数:"+jsonParam);
//请求接口地址
string _url = "https://api.yunxuetang.cn/ell/sso";
var request = (HttpWebRequest)WebRequest.Create(_url);
request.Method = "POST";
request.ContentType = "application/json;charset=UTF-8";
byte[] byteData = Encoding.UTF8.GetBytes(jsonParam);
int length = byteData.Length;
request.ContentLength = length;
Stream writer = request.GetRequestStream();
writer.Write(byteData, 0, length);
writer.Close();
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
Method.Wlog("单点登陆返回结果:"+responseString.ToString());
VideoUrlInfo videoInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<VideoUrlInfo>(responseString.ToString());
if (!string.IsNullOrWhiteSpace(videoUrl))
{
videoUrl = HttpUtility.UrlEncode(videoUrl);
videoInfo.data = videoInfo.data + "&fromurl=" + videoUrl;
}
string videoJson = JsonConvert.SerializeObject(videoInfo);
Method.Wlog("单点登陆返回结果组合json字符串:" + videoJson);
context.Response.Write(videoJson);
return;
}
catch(Exception ex)
{
VideoUrlInfo videoUrlInfo = new VideoUrlInfo();
videoUrlInfo.code = "-1";
videoUrlInfo.message += "单点登陆接口异常:" + ex.Message;
string videoJson = JsonConvert.SerializeObject(videoUrlInfo);
context.Response.Write(videoJson);
//context.Response.Write(ex.Message);
return;
}
}
/// <summary>
/// SHA256计算加密
/// </summary>
/// <param name="data"></param>
/// <returns></returns>
public string sha256(string data)
{
byte[] bytes = Encoding.UTF8.GetBytes(data);
byte[] hash = SHA256Managed.Create().ComputeHash(bytes);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
builder.Append(hash[i].ToString("x2"));
}
return builder.ToString();
}
/// <summary>
/// 单点登陆第三方视频信息
/// </summary>
public class VideoUrlInfo {
/// <summary>
/// 编码
/// </summary>
public string code { get; set; }
/// <summary>
/// 消息
/// </summary>
public string message { get; set; }
/// <summary>
/// 链接
/// </summary>
public string data { get; set; }
public string totalcount { get; set; }
}