服務端調用接口API利器之HttpClient

前言html

  以前有介紹過HttpClient做爲爬蟲的簡單使用,那麼今天在簡單的介紹一下它的另外一個用途:在服務端調用接口API進行交互。之因此整理這個呢,是由於前幾天在測試雲之家待辦消息接口的時候,有使用雲之家外出登記LightApp中的HttpHelper,以爲抽的很不錯,就拿來記錄一下,便於往後直接使用。git

HttpHelper.jar下載連接:https://pan.baidu.com/s/1d0OeVfJM_jHWjJunl7nPHQ 密碼: ujegjson

應用api

  先來介紹怎麼使用的,目的就是拿來直接用。而後在分析其內在的手法。數組

  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


    app

    其中data參數中既有整型變量又有數組,此時又該如何組裝參數呢?其中接口API已經規定內容類型ContenType爲表單類型。

    dom

    // 雲之家人員信息令牌
    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,參考測試代碼

    ide

    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
相關文章
相關標籤/搜索