Java docking Kingdee interface

Introduction to Kingdee Interface

​ First of all, let’s talk about Kingdee’s api document. Since Kingdee is developed by C#, it is very convenient to use C# to implement interface docking, because they have the tool class K/3 Cloud WebAPI for developing C# to call the interface, and encapsulate the JSON format alright. But JAVA is a headache. The JSON format and field description of the call interface are not clear, and the docking personnel are also indifferent, answering the question is wrong, and finally can only rely on online information to solve the problem. The Kingdee system is complex, here are the pitfalls I stepped on and the solutions.

​ This docking interface is mainly because the department wants to import TAPD’s work-hour record list into Kingdee’s work-hour record sheet, so here we need to call the interface of the work-hour record sheet. When I saw the interface of Kingdee, I couldn’t help complaining in my heart. Log in and view , delete can be seen at a glance, but what else is this? What about additions and modifications? Take a look at the parameters in the viewing interface. Without training, you can’t understand them at all, and some fields say they must be recorded, but they don’t need to be recorded.

insert image description here
insert image description here

After complaining, I returned to the topic. I only found out after asking the Kingdee docking staff many times.

1. View is to query a single record

2. Document query is to query multiple records according to conditions

3. Saving is to modify and add new records (there are too many fields to doubt life)

4. Formid is the ID of the form template, which needs to be checked in BOS (the designer that creates the form template)

5. The encoding is the number of the record (if you don't know it, you think it is a character encoding)

login interface

​ Because you need to know the JSON format of Kingdee to adjust the interface, the first thing that comes to mind is to use postman, so use it to test the login and cookie acquisition. This is relatively smooth and the test is successful. Among them, parameters are required, others can be left blank. Fill in the four values ​​in paramters, which are account set ID, user name, password, and language. Among them, the ID of the account set needs to be checked in the webapi of Kingdee. This is the first pit. Generally, only the user password is required to log in. However, an additional account set ID and language are used here.

insert image description here

​ After postman successfully adjusted the interface, try to use java to adjust, the interface is adjusted, but it shows that the user password is wrong. The biggest suspicion is the error of the JSON format. Afterwards, various debugging, changing the JSON package, changing the JSON format, changing UTF-8, GBK encoding, etc., have been stuck here for a day to no avail.
insert image description here

​ Later, Baidu went to the code on the Kingdee Forum and tried it, and successfully logged in! After looking at the source code, it converts JSON encoding to UNICODE encoding. It turns out that this is the reason why the user password is wrong. I can’t help complaining about Kingdee. The document is written too casually.

insert image description here

​ The following are the codes of these two classes, which encapsulate the URL of each interface and the required json format, and call which method is required for which interface

InvokeHelper.java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.json.JSONArray;
import org.json.JSONObject;

public class InvokeHelper {
    
    

        // K3 Cloud WebSite URL Example "http://192.168.19.113/K3Cloud/"
        public static String POST_K3CloudURL = "http://192.168.19.113/K3Cloud/";

        // Cookie 值
        private static String CookieVal = null;

        private static Map map = new HashMap();
        static {
    
    
                map.put("Save",
                                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc");
                map.put("View",
                                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.View.common.kdsvc");
                map.put("Submit",
                                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Submit.common.kdsvc");
                map.put("Audit",
                                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Audit.common.kdsvc");
                map.put("UnAudit",
                                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.UnAudit.common.kdsvc");
                map.put("StatusConvert",
                                "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.StatusConvert.common.kdsvc");
        }

        // HttpURLConnection
        private static HttpURLConnection initUrlConn(String url, JSONArray paras)
                        throws Exception {
    
    
                URL postUrl = new URL(POST_K3CloudURL.concat(url));
                HttpURLConnection connection = (HttpURLConnection) postUrl
                                .openConnection();
                if (CookieVal != null) {
    
    
                        connection.setRequestProperty("Cookie", CookieVal);
                }
                if (!connection.getDoOutput()) {
    
    
                        connection.setDoOutput(true);
                }
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.setRequestProperty("Content-Type", "application/json");
                DataOutputStream out = new DataOutputStream(
                                connection.getOutputStream());

                UUID uuid = UUID.randomUUID();
                int hashCode = uuid.toString().hashCode();

                JSONObject jObj = new JSONObject();

                jObj.put("format", 1);
                jObj.put("useragent", "ApiClient");
                jObj.put("rid", hashCode);
                jObj.put("parameters", chinaToUnicode(paras.toString()));
                jObj.put("timestamp", new Date().toString());
                jObj.put("v", "1.0");

                out.writeBytes(jObj.toString());
                out.flush();
                out.close();

                return connection;
        }

        // Login
        public static boolean Login(String dbId, String user, String pwd, int lang)
                        throws Exception {
    
    

                boolean bResult = false;

                String sUrl = "Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc";

                JSONArray jParas = new JSONArray();
                jParas.put(dbId);// 帐套Id
                jParas.put(user);// 用户名
                jParas.put(pwd);// 密码
                jParas.put(lang);// 语言

                HttpURLConnection connection = initUrlConn(sUrl, jParas);
                // 获取Cookie
                String key = null;
                for (int i = 1; (key = connection.getHeaderFieldKey(i)) != null; i++) {
    
    
                        if (key.equalsIgnoreCase("Set-Cookie")) {
    
    
                                String tempCookieVal = connection.getHeaderField(i);
                                if (tempCookieVal.startsWith("kdservice-sessionid")) {
    
    
                                        CookieVal = tempCookieVal;
                                        break;
                                }
                        }
                }

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                                connection.getInputStream()));
                String line;
                System.out.println(" ============================= ");
                System.out.println(" Contents of post request ");
                System.out.println(" ============================= ");
                while ((line = reader.readLine()) != null) {
    
    
                        String sResult = new String(line.getBytes(), "utf-8");
                        System.out.println(sResult);
                        bResult = line.contains("LoginResultType");
                }
                System.out.println(" ============================= ");
                System.out.println(" Contents of post request ends ");
                System.out.println(" ============================= ");
                reader.close();

                connection.disconnect();

                return bResult;
        }

        // Save
        public static void Save(String formId, String content) throws Exception {
    
    
                Invoke("Save", formId, content);
        }

        // View
        public static void View(String formId, String content) throws Exception {
    
    
                Invoke("View", formId, content);
        }

        // Submit
        public static void Submit(String formId, String content) throws Exception {
    
    
                Invoke("Submit", formId, content);
        }

        // Audit
        public static void Audit(String formId, String content) throws Exception {
    
    
                Invoke("Audit", formId, content);
        }

        // UnAudit
        public static void UnAudit(String formId, String content) throws Exception {
    
    
                Invoke("UnAudit", formId, content);
        }

        // StatusConvert
        public static void StatusConvert(String formId, String content)
                        throws Exception {
    
    
                Invoke("StatusConvert", formId, content);
        }

        private static void Invoke(String deal, String formId, String content)
                        throws Exception {
    
    

                String sUrl = map.get(deal).toString();
                JSONArray jParas = new JSONArray();
                jParas.put(formId);
                jParas.put(content);

                HttpURLConnection connectionInvoke = initUrlConn(sUrl, jParas);

                BufferedReader reader = new BufferedReader(new InputStreamReader(
                                connectionInvoke.getInputStream()));

                String line;
                System.out.println(" ============================= ");
                System.out.println(" Contents of post request ");
                System.out.println(" ============================= ");
                while ((line = reader.readLine()) != null) {
    
    
                        String sResult = new String(line.getBytes(), "utf-8");
                        System.out.println(sResult);
                }
                System.out.println(" ============================= ");
                System.out.println(" Contents of post request ends ");
                System.out.println(" ============================= ");
                reader.close();

                connectionInvoke.disconnect();
        }

        /**
         * 把中文转成Unicode码
         *
         * @param str
         * @return
         */
        public static String chinaToUnicode(String str) {
    
    
                String result = "";
                for (int i = 0; i < str.length(); i++) {
    
    
                        int chr1 = (char) str.charAt(i);
                        if (chr1 >= 19968 && chr1 <= 171941) {
    
    // 汉字范围 \u4e00-\u9fa5 (中文)
                                result += "\\u" + Integer.toHexString(chr1);
                        } else {
    
    
                                result += str.charAt(i);
                        }
                }
                return result;
        }
}

InvokeTest.java

import org.json.JSONObject;

public class InvokeTest {
    
    

	 public static void main(String[] args) throws Exception {
    
    
         InvokeHelper.POST_K3CloudURL = "";
         String dbId = "";
         String uid = "";
         String pwd = "";
         int lang = 2052;
        
         if (InvokeHelper.Login(dbId, uid, pwd, lang)) {
    
    

                 // 销售订单保存测试
                 // 业务对象Id
                 //String sFormId = "SAL_SaleOrder";
                 //需要保存的数据
                 // 如下字段可能需要根据自己实际值做修改
                 // FCustId FSalerId FMaterialId FUnitID
                 //String sContent = "{"Creator":"String","NeedUpDateFields":["FBillTypeID","FDate","FBusinessType","FSaleOrgId","FCustId","FSettleCurrId","FSalerId","SAL_SaleOrder__FSaleOrderEntry","FMaterialId","FSettleOrgIds","FUnitID","FQty","SAL_SaleOrder__FSaleOrderFinance","FSettleCurrId","FLocalCurrId","FIsIncludedTax","FBillTaxAmount","FBillAmount","FBillAllAmount","FExchangeTypeId","FExchangeRate"],"Model":{"FID":0,"FBillTypeID":{"FNumber":"XSDD01_SYS"},"FBusinessType":"NORMAL","FSaleOrgId":{"FNUMBER":"100"},"FCustId":{"FNUMBER":"CUST0001"},"FSettleCurrId":{"FNUMBER":"PRE001"},"FSalerId":{"FNUMBER":"0002"},"SAL_SaleOrder__FSaleOrderFinance":{"FExchangeRate":6.8123},"SAL_SaleOrder__FSaleOrderEntry":[{"FMaterialId":{"FNUMBER":"001"},"FSettleOrgIds":{"FNUMBER":"100"},"FUnitID":{"FNumber":"个"},"FQty":10}]}}";
                 //InvokeHelper.Save(sFormId, sContent);
                 String formid="";//QWZE_WorkingHours
                 String content="{\"Number\":\"EMPGS201911280002\"}";
        	 	 System.out.println(content);
                 InvokeHelper.View(formid, content);
                 System.out.println("hola success");
         }
	 }
}

view interface

​I failed to call this interface with postman, and failed to call it with java (tested a variety of json formats), but it can be successfully called with its own test interface. It is estimated that its own interface will carry out some formats. The verification and modification can be successful, what format is the final json sent out, due to my limited level, I don’t know, this pit can’t be solved for the time being, and I hope the great god can give me advice.

insert image description here

Guess you like

Origin blog.csdn.net/Heqinze/article/details/105842863