<UnityTheGreat;<002;UnityWebRequest获取Alibaba的时间戳
Posted MirzkisD1Ex0
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了<UnityTheGreat;<002;UnityWebRequest获取Alibaba的时间戳相关的知识,希望对你有一定的参考价值。
引用了Newtonsoft.dll、System、Networking。
ConvertStringToDateTime()完全没有用到,只是为了方便验证时间戳是否正确,可以删除。
放弃使用WWW,而选择了使用UnityWebRequest-Get。
从Taobao那边Get到时间戳,然后用Newtonsoft解析json并debug出来,理论上Ctrl+C+V就能拿去用了。
内容不多,也懒得详细解释了,欢迎随意取用,希望能够帮到诸位。
#region Environment
Windows 10 20H2
Unity 2020.3.7f1c1 LTS
VSCode 1.56.2
https://github.com/MirzkisD1Ex0/UnityTheGreat.git
#endregion
#region Code↓↓↓
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using UnityEngine.Networking;
/// <summary>
///
/// </summary>
/// https://tool.lu/timestamp/
public class TimeChecker : MonoBehaviour
{
public string StampURL = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp";
private void Start()
{
StartCoroutine(GetTimeStamp(StampURL));
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
private IEnumerator GetTimeStamp(string stampURL)
{
UnityWebRequest webRequest = UnityWebRequest.Get(stampURL);
yield return webRequest.SendWebRequest();
if (webRequest.result == UnityWebRequest.Result.ProtocolError || webRequest.result == UnityWebRequest.Result.ConnectionError)
{
Debug.Log(webRequest.error);
}
JObject jb = JObject.Parse(webRequest.downloadHandler.text);
Debug.Log(jb["data"]["t"]); // 时间戳
long now = long.Parse(jb["data"]["t"].ToString());
if (now >= 1621419596)
{
Debug.Log("时间已过期");
}
Debug.Log(now);
}
/// <summary>
/// 时间戳转为C#格式时间
/// </summary>
/// <param name="timeStamp"></param>
/// <returns></returns>
private DateTime ConvertStringToDateTime(string timeStamp)
{
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
long lTime = long.Parse(timeStamp + "0000");
TimeSpan toNow = new TimeSpan(lTime);
return dtStart.Add(toNow);
}
}
#endregion
以上是关于<UnityTheGreat;<002;UnityWebRequest获取Alibaba的时间戳的主要内容,如果未能解决你的问题,请参考以下文章