java调用接口小结

最近因为系统需要,需要采用 http 调用对方的服务器接口,GET,POST 都有,记录一下
GET 请求:

/**
     * 功能描述: get 请求
     * @param: [url]
     * @return: JSONObject
     * @auther: lsr
     * @date: 2018/11/14 16:59
     */
    public JSONObject doGet(String url) {
        // 1.使用默认的配置的httpclient
        JSONObject mapTypes = null;
        CloseableHttpClient client = HttpClients.createDefault();
        // 2.使用get方法
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;

        try {
            // 3.执行请求,获取响应
            response = client.execute(httpGet);

            // 4.获取响应的实体内容
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                mapTypes = JSON.parseObject(EntityUtils.toString(entity, "utf-8"));
                if (null != mapTypes.get("errmsg")) {
                    logger.info((String) mapTypes.get("errmsg"));
                }
                return mapTypes;
            }
            EntityUtils.consume(entity);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("获取信息失败:" + e.getMessage());
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

POST 请求:

/**
     *      * post请求
     *      * @param url
     *      * @param json
     *      * @return
     */
    public JSONObject doPost(String url, JSONObject json) throws Exception{
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        String result = null;
        try {
            post.addHeader("Content-type","application/json; charset=utf-8");
            post.setHeader("Accept", "application/json");
            post.setEntity(new StringEntity(json.toString(), Charset.forName("UTF-8")));
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = res.getEntity();
                result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = JSONObject.parseObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            client.close();
        }
        return response;
    }

自己将服务封装为 POST 请求:

/**
     * 功能描述: 调用钉钉服务器接口,添加用户信息
     * @param: [request, name, mobile]
     * @return: java.lang.String
     * @auther: lsr
     * @date: 2018/11/8 14:20
     */
    @RequestMapping(value="/addUser",method= RequestMethod.POST)
    private JSONObject addUser(@RequestBody(required=false) JSONObject jsonObject){
        JSONObject resultObject = null;
        if(jsonObject == null || jsonObject.equals(null)){
            resultObject.put("errcode",9999);
            resultObject.put("errmsg","调用钉钉服务器存在错误,用户参数为空");
            logger.error("调用钉钉服务器存在错误,用户参数为空");
            return resultObject;
        }
        JSONObject jsonParam = new JSONObject();
        jsonParam.put("name", jsonObject.getString("name"));
        jsonParam.put("mobile", jsonObject.getString("mobile"));
        jsonParam.put("department", new int[]{1});
        String accessToken = dingAuthHelpUtil.getAccessToken();
        try {
            resultObject = dingAuthHelpUtil.doPost("https://oapi.dingtalk.com/user/create?access_token=" + accessToken, jsonParam);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            logger.error("调用钉钉服务器失败");
        }
        return resultObject;
    }

你可能感兴趣的:(java调用接口小结)