API-一次登录多次使用简单示例原创
8人赞赏了该文章
4825次浏览
编辑于2022年05月26日 10:36:07
说明
API登录一次默认会保持20分钟会话,如果20分钟内会调用其他接口,会话时间会重新算;即使后台处理时间超长,或后台把会话清理了,返回的结果也会提示会话丢失,只需要重新登录即可,所以没有必要每次调用其他接口之前去调用登录接口。
示例代码
1. 下面的代码简单演示了登录一次,保存多次的情况。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Newtonsoft.Json.Linq; using Kingdee.BOS.WebApi.Client; namespace ConsoleTest { public class KingdeeClient { //服务器地址 private const string _serviceUrl = "http://localhost:2800/k3cloud/"; //平台封装的客户端组件 private K3CloudApiClient _client; //是否登录过 private bool _logined = false; //静态锁,防止并发 private static object staticLock = new object(); /// <summary> /// 构造函数 /// </summary> public KingdeeClient() { // 10为客户端请求超时时间 this._client = new K3CloudApiClient(_serviceUrl, 10); } /// <summary> /// 公共保存接口 /// </summary> /// <returns></returns> public string SaveData(string data) { var sResult = ""; if (this.Login()) //判断是否已登录 { bool isContinue = false; sResult = this.SaveBill(data,ref isContinue); int index = 0; while (isContinue && index < 2) //index < 2 最多再次循环调用次数, { isContinue = false; sResult = this.SaveBill(data, ref isContinue); index++; } } return sResult; } /// <summary> /// 保存具体单据 /// </summary> /// <param name="isContinue"></param> private string SaveBill(string data,ref bool isContinue) { var sResult = this._client.Save("formId", data); var responseStatus = JObject.Parse(sResult)["Result"]["ResponseStatus"]; var isSuccess = responseStatus["IsSuccess"].Value<bool>(); if (!isSuccess) { var msgCode = responseStatus["MsgCode"].Value<int>(); if (msgCode == 1)//如何是会话丢失,则重新登录 { Login(true); //重新登录 isContinue = true; } else { //其他情况,则记录日志或再次调用啥的 } } return sResult; } /// <summary> /// 登录操作 /// </summary> /// <returns></returns> private bool Login(bool isForse = false) { lock (staticLock) { if (isForse) { this._logined = false; } if (!this._logined) { this._logined = true; var loginResult = this._client.ValidateLogin("账套Id", "用户名", "密码", 2052); var resultType = JObject.Parse(loginResult)["LoginResultType"].Value<int>(); if (resultType == 1) { return true; } throw new Exception(loginResult); } } return true; } } }
2. 客户端调用
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleTest { public class Program { public static void Main(string[] args) { KingdeeClient kClient = new KingdeeClient(); foreach(var data in lstData) { var saveResult = kClient.SaveData(data); } Console.Write(saveResult); Console.ReadKey(); } } }
推荐阅读