首页 > 技术文章 > 服务端调用接口API利器之HttpClient

lyc-smile 2018-08-06 10:14 原文

前言

  之前有介绍过HttpClient作为爬虫的简单使用,那么今天在简单的介绍一下它的另一个用途:在服务端调用接口API进行交互。之所以整理这个呢,是因为前几天在测试云之家待办消息接口的时候,有使用云之家外出登记LightApp中的HttpHelper,觉得抽的很不错,就拿来记录一下,便于日后直接使用。

HttpHelper.jar下载链接:https://pan.baidu.com/s/1d0OeVfJM_jHWjJunl7nPHQ 密码: ujeg

应用

  先来介绍怎么使用的,目的就是拿来直接用。然后在分析其内在的手法。

  1. 使用Json格式的参数进行请求
    Json参数工具使用的是alibaba fastjson-1.2.43.jar
        /**
         * gateway发送json参数POST请求
         * 
         * @param url
         * @param parm
         * @return
         * @throws Exception
         */
        public static String gatewayRequestJson(String url, String parm) throws Exception {
            Map headers = new HashMap(1);
            headers.put("Content-Type", APPLICATION_JSON);
            return HttpHelper.post(headers, parm, url, timeoutMillis);
        }
    View Code

    调用云之家待办消息APIdemo


     

    /*************************S测试参数组装************/
    // 推送待办消息
            String scope = "app"; // String scope = "app"; resGroupSecret  待办
            String eid = "10272669";
            String appId = "500051942";
            String sourceId = "jzyj2eeappdemo";
            String content = "xxx的360°需要您评核";
            String title = "待办测试";
            String headImg = "https://www.yunzhijia.com/space/c/photo/load?id=5b17b7efe4b00656b6c41a50";
            String url = "https://open.yunzhijia.com/gitbook-wiki/server-api/newTodo.html?q=";
    
            List params = new ArrayList();
            Map map = new HashMap();
            Map map2 = new HashMap();
            map2.put("DO", 0);
            map2.put("READ", 0);
            map.put("status", map2);
            map.put("openId", "5b17b7efe4b00656b6c41a50");
            params.add(map);
    
            Map parm = new HashMap(2);
            parm.put("appId", appId);
            parm.put("sourceId", sourceId);
            parm.put("content", content);
            parm.put("title", title);
            parm.put("headImg", headImg);
            parm.put("url", url);
            parm.put("params", params);
    
    /*************************E测试参数组装************/
    
    //获取云之家授权令牌accessToken
    String accessToken = getAccessToken(appId, appSecret, eid, scope);  //待办accessToken
    
    // 组装云之家请求API url
     String requestUrl = gatewayHost.concat("/newtodo/open/generatetodo.json?accessToken=").concat(accessToken);
    
    
    // 发送请求
    Object res = JSONObject
                    .parseObject(gatewayRequestJson(requestUrl, JSONObject.toJSONString(parm)));

     

  2. 表单形式参数发送请求 application/x-www-form-urlencoded
     /**
         * gateway发送application/x-www-form-urlencoded参数POST请求
         * 
         * @param url
         * @param parm
         * @return
         * @throws Exception
         */
        public static String gatewayRequest(String url, Map parm) throws Exception {
            Map headers = new HashMap(1);
            headers.put("Content-Type", APPLICATION_X_WWW_FORM_URLENCODED);
            return HttpHelper.post(headers, parm, url, timeoutMillis);
        }

    调取云之家人员指定人员信息demo


    其中data参数中既有整型变量又有数组,此时又该如何组装参数呢?其中接口API已经规定内容类型ContenType为表单类型。

    // 云之家人员信息令牌
    String accessToken = getAccessToken(appId, appSecret, null, scope);
    
    // 获取人员信息API url
            String personUrl = gatewayHost.concat("/openimport/open/person/get?accessToken=").concat(accessToken);
    /**************S组装表单参数**************************/
            Map paramters = new HashMap(2);
            paramters.put("eid", eid);
            JSONObject jo = new JSONObject();
            jo.put("eid", eid);
            jo.put("type", 0);
    
            JSONArray ja = new JSONArray();
            ja.add("123321231231");//电话号码
    
            jo.put("array", ja);
    
            paramters.put("nonce", UUID.randomUUID().toString());
            paramters.put("data", jo.toString());
    /***************E组装表单参数*************************/
    
    //请求API
            String res = gatewayRequest(personUrl, paramters);
    
            Object parseObject = JSONObject.parseObject(res);
    
    
    
    
        

     
    获取云之家授权令牌accessToken,参考测试代码

    public static String getAccessToken(String appId, String secret, String eid, String scope) {
            TokenBean tokenBean = new TokenBean();
            // 判断当前token是否在有效期内
            if (tokenBean != null && tokenBean.getAccessToken() != null && scope.equals(tokenBean.getScope())
                    && StringUtils.isNotBlank(eid) && eid.equals(tokenBean.getEid())) {
                if ((System.currentTimeMillis() - tokenBean.getUpdateTime().getTime())
                        / 1000 < (tokenBean.getExpireIn() - 300)) {
                    // logger.debug("返回有效期内的access_token: {}", tokenBean.getAccessToken());
                    return tokenBean.getAccessToken();
                }
            }
    
            // 如果没有token信息或者已经过期, 重新从api获取
            final String[] SCOPES = { "app", "team", "resGroupSecret" };
            String timestamp = String.valueOf(System.currentTimeMillis());
            Map parm = new HashMap(5);
            parm.put("scope", scope);
            parm.put("timestamp", timestamp);
    
            if (scope.equals(SCOPES[0])) {
                parm.put("appId", appId);
            } else if (scope.equals(SCOPES[1])) {
                parm.put("eid", eid);
            }
            if (scope.equals(SCOPES[2])) {
                // 获取resGroupSecret秘钥
                parm.put("eid", eid);
                secret = erpSecret;
            }
    
            parm.put("secret", secret);
            String url = gatewayHost.concat("/oauth2/token/getAccessToken");
            JSONObject result = null;
            try {
                result = JSONObject
                        .parseObject(GatewayAuth2.gatewayRequestJson(url, JSONObject.toJSONString(parm)))
                        .getJSONObject("data");
            } catch (Exception e) {
                e.printStackTrace();
                // logger.error("获取access_token信息失败!, 返回null");
            }
    
            // logger.debug("获取access_token返回数据: {}", result);
            tokenBean = JSON.toJavaObject(result, TokenBean.class);
    
            if (tokenBean != null && tokenBean.getAccessToken() != null) {
                tokenBean.setUpdateTime(new Date());
                tokenBean.setScope(scope);
                tokenBean.setEid(eid);
                // tokenDao.setToken(tokenBean); // 缓存获取的token信息
                // logger.debug("返回新获取的access_token: {}", tokenBean.getAccessToken());
                return tokenBean.getAccessToken();
            }
            // logger.error("获取access_token信息失败!, 返回null");
            return null;
    
        }
    View Code

     

     




 

推荐阅读