Java对接腾讯智慧校园开放平台,idea完整项目

Posted 秋9

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java对接腾讯智慧校园开放平台,idea完整项目相关的知识,希望对你有一定的参考价值。

Java对接腾讯智慧校园开放平台,直接上代码。

关键代码如下:

public class Sign {

    private static final char[] HEXES = {
            '0', '1', '2', '3',
            '4', '5', '6', '7',
            '8', '9', 'a', 'b',
            'c', 'd', 'e', 'f'
    };

    public static String bytes2Hex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }

        StringBuilder hex = new StringBuilder();

        for (byte b : bytes) {
            hex.append(HEXES[(b >> 4) & 0x0F]);
            hex.append(HEXES[b & 0x0F]);
        }

        return hex.toString();
    }

    public static String getSign(String secretKey, String method, String url, Map<String, Object> param, String body)
            throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
        // 1. 拼接签名串
        // params 排序
        String[] keys = new String[param.size()];
        System.arraycopy(param.keySet().toArray(), 0, keys, 0, keys.length);
        Arrays.sort(keys);

        List<String> paramsPairs = new ArrayList<String>(keys.length);
        for(String key : keys) {
            paramsPairs.add(key + "=" + param.get(key));
        }

        String paramsStr  = StringUtils.join(paramsPairs, "&");

        StringBuilder commonStr = new StringBuilder(method).append(url).append("?").append(paramsStr);
        if ((method.equals("POST") || method.equals("PUT")) && body.length() > 0) {
            commonStr.append("&Data=").append(body);
        }

        String rawStr = commonStr.toString();
        System.out.println(rawStr);

        // 2. hmac_sha1 签名

        SecretKey secretKeyS = new SecretKeySpec(secretKey.getBytes("utf8"), "HmacSHA1");
        Mac mac = Mac.getInstance(secretKeyS.getAlgorithm());
        mac.init(secretKeyS);
        byte[] rawHmac = mac.doFinal(rawStr.getBytes("utf8"));
        String b16encoded = bytes2Hex(rawHmac);
        return URLEncoder.encode(b16encoded, "utf8");
    }

    public static String joinRequest(Map params, String url, String sign) {
        List<String> paramsPairs = new ArrayList<String>(params.size()+1);
        for(Object key : params.keySet()) {
            paramsPairs.add(key + "=" + params.get(key));
        }
        paramsPairs.add("Sign" + "=" + sign);
        StringBuilder commonStr = new StringBuilder(url).append("?").append(StringUtils.join(paramsPairs, "&"));
        return commonStr.toString();
    }

    public static String sendGetRequest(String url) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        Response response = okHttpClient.newCall(new Request.Builder().url(url).build()).execute();
        return response.body().string();
    }

    public static String sendPostRequest(String url, JSONObject data) throws IOException {
        OkHttpClient okHttpClient = new OkHttpClient();
        MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create( MediaType.parse("application/json; charset=utf-8"),data.toString());
        Request request = new Request.Builder()
                .addHeader("Content-Type", "application/json")
                .url(url)
                .post(body)
                .build();
        Response response = okHttpClient.newCall(request).execute();
        return response.body().string();
    }

    public static void main(String[] args) {
        String secreteKey = "914f572cbd2901c517e4ddfb0a4f8ddf";

        int nonce = new Random().nextInt(100000000);
        long timestamp = System.currentTimeMillis();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("Action", "GetOrgInfo");
        params.put("SecretId", 800);
        params.put("Nonce", nonce);
        params.put("OrgId", 1003418);
        params.put("Timestamp", timestamp);

        String url = "oapi.campus.qq.com/v2/user";

        try {
            //  GET请求
            String signStr = getSign(secreteKey, "GET", url, params, "");
            System.out.println(signStr);

            String requestUrl = joinRequest(params, "https://" + url, signStr);
            System.out.println(requestUrl);
            String responseStr = sendGetRequest(requestUrl);
            System.out.println(responseStr);

            //  POST请求
            JSONObject data = new JSONObject();
            JSONArray array = new JSONArray();
            array.put("58po4mj5443");
            data.put("OrgUserId", array);

            nonce = new Random().nextInt(100000000);
            timestamp = System.currentTimeMillis();
            params.put("Action", "GetUsersInfo");
            params.put("Timestamp", timestamp);
            params.put("Nonce", nonce);

            signStr = getSign(secreteKey, "POST", url, params, data.toString());
            System.out.println(signStr);

            requestUrl = joinRequest(params, "https://" + url, signStr);
            System.out.println(requestUrl);

            responseStr = sendPostRequest(requestUrl, data);
            System.out.println(responseStr);

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

运行结果为:

报“应用未安装,请先安装应用,或联系管理员”的解决方法,请见https://blog.csdn.net/jlq_diligence/article/details/116355700

解决后的运行结果如下:

GEToapi.campus.qq.com/v2/user?Action=GetOrgInfo&Nonce=35163864&OrgId=1003418&SecretId=1003418&Timestamp=1619952745134
7366895980bec368e3f013f1c6f7331d44dcd3f8
https://oapi.campus.qq.com/v2/user?Nonce=35163864&OrgId=1003418&Action=GetOrgInfo&SecretId=1003418&Timestamp=1619952745134&Sign=7366895980bec368ebf013f1c6f7381d44dcd3f8
{"RequestId":"f935c2637be8c834687aa0b0577aa233","ErrorCode":"OK", "Data": {"Name":"北京**公司测试学校1590373497","Logo":"https://sc-developer-125.cos.ap-guangzhou.myqcloud.com/develop-system-pic-dir/sp-all/28347-logo.png","Type":"SCHOOL","Country":"中国","Province":"北京市","City":"北京市","Area":"海淀区","EduType":2,"SchoolCategory":[3,9],"Code":"9f4e35c9354","Level":0,"ProvinceCode":010000,"CityCode":010300,"AreaCode":010305,"ProvinceId":"","CityId":"","AreaId":"","Source":0,"AppTemplate":1,"CorpId":""}}

完整Java项目,请见http://www.zrscsoft.com/sitepic/12132.html

以上是关于Java对接腾讯智慧校园开放平台,idea完整项目的主要内容,如果未能解决你的问题,请参考以下文章

Java对接腾讯教育开放平台,idea完整项目

Java对接腾讯教育开放平台,idea完整项目

Java对接腾讯智慧校园开放平台报“应用未安装,请先安装应用,或联系管理员”的解决方法

Java对接腾讯智慧校园开放平台报“应用未安装,请先安装应用,或联系管理员”的解决方法

组建一个智慧校园监控管理平台,总共需要几步?

智慧校园智慧教育大数据平台