金碟云星空API

package org.jeecg.common.k3cloud;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * K3Cloud Api
 * @author immi
 * @date 2022-09-13
 */
public class K3CloudClientUtil {
    //请求Url
    public static String POST_K3CloudURL = "http://47.106.121.120/k3cloud/";
    //Cookie
    private static String CookieVal = null;
    private static Map<String, String> 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");
        map.put("ExecuteBillQuery", "Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.ExecuteBillQuery.common.kdsvc");
    }

    /**
     * Http请求
     * @param url
     * @param paras
     * @return
     * @throws Exception
     */
    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;
    }

    /**
     * 把中文转成Unicode码
     * @param s
     * @return
     */
    public static String chinaToUnicode(String s) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c >= ' ' && c <= '~') {
                sb.append(c);
            } else {
                sb.append(char2Unicode(c));
            }
        }
        System.out.println("转编码字符======>" + sb);
        return sb.toString();
    }

    /**
     * 转化编码
     * @param c
     * @return
     */
    private static String char2Unicode(char c) {
        StringBuffer sb = new StringBuffer();
        sb.append("\\u");

        int j = c >>> '\b';
        String tmp = Integer.toHexString(j);
        if (tmp.length() == 1)
            sb.append("0");
        sb.append(tmp);
        j = c & 0xFF;
        tmp = Integer.toHexString(j);
        if (tmp.length() == 1)
            sb.append("0");
        sb.append(tmp);
        return sb.toString();
    }

    /**
     * 登录
     * @param dbId
     * @param user 用户名
     * @param pwd  密码
     * @param lang 语言
     * @return
     * @throws Exception
     */
    public static boolean Login(String dbId, String user, String pwd, int lang) throws Exception {
        boolean result = false;

        String line;

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

        JSONArray jParas = new JSONArray();
        jParas.add(dbId);
        jParas.add(user);
        jParas.add(pwd);
        jParas.add(lang);

        HttpURLConnection connection = initUrlConn(RequestUrl, jParas);

        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()));

        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ");
        System.out.println(" ============================= ");
        while ((line = reader.readLine()) != null) {
            result = line.contains("\"LoginResultType\":1");
        }
        System.out.println(" ============================= ");
        System.out.println(" Contents of post request ends ");
        System.out.println(" ============================= ");
        reader.close();

        connection.disconnect();

        return result;
    }

    public static JSONObject Save(String formId, String content) throws Exception { return Invoke("Save", formId, content); }
    public static JSONObject View(String formId, String content) throws Exception { return Invoke("View", formId, content); }
    public static JSONObject ExecuteBillQuery(String content) throws Exception { return Invoke("ExecuteBillQuery", content); }
    public static JSONObject Submit(String formId, String content) throws Exception { return Invoke("Submit", formId, content); }
    public static JSONObject Audit(String formId, String content) throws Exception { return Invoke("Audit", formId, content); }
    public static JSONObject UnAudit(String formId, String content) throws Exception { return Invoke("UnAudit", formId, content); }
    public static JSONObject StatusConvert(String formId, String content) throws Exception { return Invoke("StatusConvert", formId, content); }

    /**
     * 保存、提交、审核、反审核
     * @param type    操作方式
     * @param formId  表单id
     * @param data    数据
     * @return jsonObject
     * @throws Exception
     */
    private static JSONObject Invoke(String type, String formId, String data) throws Exception {

        //输出对象
        JSONObject response = new JSONObject(true);
        response.put("Data",null);

        JSONArray jsonArray = null;

        String requestUrl = ((String)map.get(type)).toString();

        JSONArray param = new JSONArray();
        param.add(formId);
        param.add(data);

        String line;

        HttpURLConnection connectionInvoke = initUrlConn(requestUrl, param);

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

        StringBuilder sb = new StringBuilder();

        while ((line = reader.readLine()) != null) {
            sb.append(new String(line.getBytes(), "utf-8"));
        }
        //[[{"Result":{"ResponseStatus":{"ErrorCode":500,"IsSuccess":false,"Errors":[{"FieldName":null,"Message":"元数据中标识为FBillNos的字段不存在","DIndex":0}],"SuccessEntitys":[],"SuccessMessages":[],"MsgCode":9}}}]]
        //[]
        JSONObject jsonObject = JSONObject.parseObject(sb.toString());
        //result json
        String result = jsonObject.getString("Result");
        //result object
        Map<String,Object> map = (Map<String, Object>)JSONObject.parseObject(result);
        //ResponseStatus object
        Map<String,Object> responseStatus = (Map<String, Object>) map.get("ResponseStatus");
        //IsSuccess
        Boolean isSuccess = (Boolean) responseStatus.get("IsSuccess");
        if(isSuccess){
            response.put("Success",true);
            response.put("BillNo",map.get("Number"));
            JSONArray xx = (JSONArray) responseStatus.get("SuccessEntitys");
            String a = "";
        }
        else{
            List<Map<String,Object>> errors = (List<Map<String, Object>>) responseStatus.get("Errors");
            response.put("Success",false);
            response.put("Message", JSON.toJSONString(errors));
        }

        reader.close();

        connectionInvoke.disconnect();

        return response;
    }

    /**
     * 查询
     * @param type    操作方式
     * @param data    数据
     * @return jsonArray
     * @throws Exception
     */
    private static JSONObject Invoke(String type, String data) throws Exception {
        //输出对象
        JSONObject response = new JSONObject(true);
        response.put("Data",null);

        String requestUrl = ((String)map.get(type)).toString();

        JSONArray param = new JSONArray();
        param.add(data);

        String line;

        HttpURLConnection connectionInvoke = initUrlConn(requestUrl, param);

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

        StringBuilder sb = new StringBuilder();

        while ((line = reader.readLine()) != null) {
            sb.append(new String(line.getBytes(), "utf-8"));
        }

        String json = sb.toString();
        //[[{"Result":{"ResponseStatus":{"ErrorCode":500,"IsSuccess":false,"Errors":[{"FieldName":null,"Message":"元数据中标识为FBillNos的字段不存在","DIndex":0}],"SuccessEntitys":[],"SuccessMessages":[],"MsgCode":9}}}]]
        //[]
        //[["CGSL000015",1],["CGSL000016",1]]
        JSONArray jsonArray = JSONArray.parseArray(json);
        try{
            if(json.contains("\"IsSuccess\":false")){
                response.put("Message", json);
                response.put("Success",false);
                try{
                    //TODO 后面优化
                    //第一层
                    JSONArray jsonArrayOne = jsonArray.getJSONArray(0);
                    //Result对象
                    JSONObject jsonObjectResult = jsonArrayOne.getJSONObject(0);
                    //Errors数组
                    JSONArray jsonArrayErrors =  jsonObjectResult.getJSONObject("Result").getJSONObject("ResponseStatus").getJSONArray("Errors");
                    //Errors JSON
                    JSONObject jsonObjectError = jsonArrayErrors.getJSONObject(0);
                    //Errors 异常
                    response.put("Message", jsonObjectError.getString("Message"));
                }
                catch (Exception exx){
                    //无需异常处理
                }
            }else{
                response.put("Success",true);
                response.put("Data",JSONArray.parseArray(sb.toString()));
            }


        }catch (Exception ex){
            response.put("Success",false);
            response.put("Data",ex.getMessage());
        }

        reader.close();

        //resultJson.getJSONObject("Result").getJSONObject("ResponseStatus").getJSONArray("Errors"));

        connectionInvoke.disconnect();

        return response;
    }

    public static JSONObject JsonObjectNumber(int value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("FNumber",value);
        return  jsonObject;
    }

    public static JSONObject JsonObjectNumber(String value)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("FNumber",value);
        return  jsonObject;
    }

    public static JSONArray empty(){
        JSONArray jsonArray = new JSONArray();
        return jsonArray;
    }

    public static String getDate() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值