调用接口登录禅道_Java调用禅道api接口查询以及创建任务(傻瓜式复制粘贴--专业版禅道页面调用)

背景:系统需要调用禅道的接口进行工单的创建,并对工单进行附件上传等信息的操作。禅道接口为http接口,每次请求都需要带上zentaosid进行请求。

1.配置常量类

/**
 * @ClassName ZenTaoConstants
 * @Description 禅道接口调用地址常量
 * @Author hyh
 * @Date 2022/6/29 8:56
 * @Version 1.0
 */
public class ZenTaoConstants {

    /**
     * http get请求
     */
    public static final String HTTP_GET_METHOD = "GET";

    /**
     * http post请求
     */
    public static final String HTTP_POST_METHOD = "POST";
    /**
     * 禅道服务网地址
     */
    public static final String ZENTAO_DOMAIN_URL = "http://**.com/zentao/www/index.php?t=json";

    /**
     * 获取禅道session
     */
    public static final String ZENTAO_GET_SESSION_URL = ZENTAO_DOMAIN_URL + "&m=api&f=getSessionID";

    /**
     * 禅道登录
     */
    public static final String ZENTAO_POST_LOGIN_URL = ZENTAO_DOMAIN_URL + "&m=user&f=login&account={0}&password={1}&zentaosid={2}";

    /**
     * 获取用户列表
     */
    public static final String ZENTAO_GET_USERLIST_URL = "http://****.com/zentao/www/api.php/v1/users?page=1&limit=1000&zentaosid={0}";

    /**
     * 创建禅道任务单
     */
    public static final String ZENTAO_POST_CREATE_ORDER_URL = ZENTAO_DOMAIN_URL + "&m=task&f=create&executionID={0}&storyID=0&moduleID=0&zentaosid={1}";

    /**
     * 给工单添加备注
     */
    public static final String ZENTAO_POST_ADD_ORDER_COMMENT_URL = ZENTAO_DOMAIN_URL + "&m=action&f=comment&objectType=task&objectID={0}&zentaosid={1}";

    /**
     * 关闭工单,并添加备注
     */
    public static final String ZENTAO_POST_CLOSE_ORDER_URL = ZENTAO_DOMAIN_URL + "&m=task&taskID={0}&f=edit&zentaosid={1}";

    /**
     * 批量关闭工单
     */
    public static final String ZENTAO_GET_CLOSE_BATCH_ORDER_URL = ZENTAO_DOMAIN_URL + "&m=task&f=batchClose&skipTaskIdList={0}&zentaosid={1}";

    /**
     * 删除工单
     */
    public static final String ZENTAO_GET_DELETE_ORDER_URL = ZENTAO_DOMAIN_URL + "&m=task&taskID={0}&executionID={1}&f=delete&zentaosid={2}&confirm=yes";

}

2.封装请求方法

/**
 * 禅道api
 *
 * @author wangshuxue
 * @date 2021/3/17
 */
public interface IZenTaoService {

    /**
     * @param
     * @return String
     * @description: 禅道登录
     * @author hyh
     * @date 2022/7/13 9:43
     */
    String loginZenTao() throws IOException;

    /**
     * 获取禅道用户信息
     *
     * @return com.vcom.vpms.model.dto.ResponseBean
     * @author wangshuxue
     * @params []
     * @date 2021/3/17
     */
    List listZentaoUsers() throws IOException;

    /**
     * @param
     * @return String
     * @description: 获取禅道session,默认时间是24分钟
     * @author hyh
     * @date 2022/7/13 9:50
     */
    String getZenTaoSession();

    /**
     * @param
     * @return String
     * @description: 创建禅道任务单
     * @author hyh
     * @date 2022/7/13 9:53
     */
    String createOrder( MultipartFile[] files, AcceptOrder acceptOrder ) throws IOException;

    /**
     * @param
     * @return
     * @description: 给工单添加备注
     * @author hyh
     * @date 2022/7/13 14:10
     */
    Boolean addComment( AcceptOrderRemark acceptOrderRemark ) throws IOException;

    /**
     * @param
     * @return
     * @description: 关闭工单,并添加备注
     * @author hyh
     * @date 2022/7/13 13:34
     */
    Boolean closeOrder( AcceptOrderRemark orderRemark ) throws IOException;

    /**
     * @param ids
     * @return
     * @description: 批量关闭工单
     * @author hyh
     * @date 2022/7/13 13:34
     */
    Boolean closeBatchOrder( String ids ) throws IOException;

    /**
     * @param
     * @return
     * @description: 删除工单
     * @author hyh
     * @date 2022/7/13 13:34
     */
    Boolean delOrder( AcceptOrder acceptOrder ) throws IOException;
}

3.创建方法实现类

package com.vcom.pmfr.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.vcom.pmfr.enums.ZenTaoOptionEnum;
import com.vcom.pmfr.enums.ZenTaoTaskStatusEnum;
import com.vcom.pmfr.exception.BaseException;
import com.vcom.pmfr.mapper.SDictDataMapper;
import com.vcom.pmfr.model.common.Constant;
import com.vcom.pmfr.model.common.ZenTaoConstants;
import com.vcom.pmfr.model.entity.AcceptOrder;
import com.vcom.pmfr.model.entity.AcceptOrderRemark;
import com.vcom.pmfr.model.entity.SDictData;
import com.vcom.pmfr.model.entity.SysUser;
import com.vcom.pmfr.model.zentao.ZenTaoClientVo;
import com.vcom.pmfr.model.zentao.ZenTaoUserVo;
import com.vcom.pmfr.service.IZenTaoService;
import com.vcom.pmfr.util.RedisUtil;
import com.vcom.pmfr.util.UserUtil;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.SocketTimeoutException;
import java.text.MessageFormat;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class ZenTaoServiceImpl implements IZenTaoService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private UserUtil userUtil;

    private static final Long ZENTAO_SESSION_EXPIRE_TIME = 20 * 60L;

    //禅道客服运维管理账号
    @Value("${zentao.account}")
    private String ZEN_TAO_ADMIN_ACCOUNT;

    //禅道客服运维管理密码
    @Value("${zentao.password}")
    private String ZEN_TAO_ADMIN_PASSWORD;

    /**
     * 设置超时时间
     */
    private static final int CONNECT_TIMEOUT = 30;
    private static final int READ_TIMEOUT = 12;
    private static final int WRITE_TIMEOUT = 12;

    @Autowired
    private SDictDataMapper sDictDataMapper;

    /**
     * 获取禅道用户信息
     *
     * @return com.vcom.vpms.model.dto.ResponseBean
     * @author wangshuxue
     * @params []
     * @date 2021/3/17
     */
    @Override
    public List listZentaoUsers() throws IOException {
        List jsonList = new ArrayList();
        //获取禅道session,每次刷新登录
        String zentaosid = loginZenTao();
        //拼接获取禅道用户地址参数
        String userUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_GET_USERLIST_URL, zentaosid);
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(userUrl);
        zenTaoClientVo.setBody(null);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_GET_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_GETUSER.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            String users = jsonObject.getString("users");
            if (StringUtils.isNotEmpty(users)) {
                jsonList = JSONArray.parseArray(users, ZenTaoUserVo.class);
            }
        }
        return jsonList;
    }

    /**
     * @param
     * @return String
     * @description: 获取禅道session,默认时间是24分钟
     * @author hyh
     * @date 2022/7/13 9:50
     */
    @Override
    public String getZenTaoSession() {
        String zentaosid = null;
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(ZenTaoConstants.ZENTAO_GET_SESSION_URL);
        zenTaoClientVo.setBody(null);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_GET_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_SESSION.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            String tmp = StringEscapeUtils.unescapeEcmaScript(jsonObject.getString("data"));
            JSONObject object = JSONObject.parseObject(tmp);
            zentaosid = object.getString("sessionID");
            //将禅道sessionid放入缓存,设置平台20分钟失效,禅道24分钟失效
            redisUtil.set(getZenTaoKey(), zentaosid, ZENTAO_SESSION_EXPIRE_TIME);
        }
        return zentaosid;
    }

    /**
     * @param
     * @return String
     * @description: 禅道登录
     * @author hyh
     * @date 2022/7/13 9:43
     */
    @Override
    public String loginZenTao() throws IOException {
        //获取禅道session
        String zentaosid = getZentaoSid();
        //创建请求
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        //获取用户禅道账户密码
        SysUser sysUser = getLoginUserInfo();
        //拼接登录地址参数
        String loginUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_POST_LOGIN_URL, sysUser.getChandaoAccount(), sysUser.getChandaoPassword(), zentaosid);
//        String loginUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_POST_LOGIN_URL, ZEN_TAO_ADMIN_ACCOUNT, ZEN_TAO_ADMIN_PASSWORD, zentaosid);
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(loginUrl);
        zenTaoClientVo.setBody(body);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_POST_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_LOGIN.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isEmpty(jsonObject)) {
            redisUtil.hdel(getZenTaoKey());
            log.warn("禅道token未获取到");
            throw new BaseException("禅道token未获取到");
        }
        if (jsonObject.containsKey("status") && "failed".equals(jsonObject.getString("status"))) {
            redisUtil.hdel(getZenTaoKey());
            log.warn("禅道token未获取到:" + jsonObject.getString("reason"));
            throw new BaseException(jsonObject.getString("reason"));
        }
        return zentaosid;
    }

    /**
     * @param
     * @return String
     * @description: 创建禅道任务单
     * @author hyh
     * @date 2022/7/13 9:53
     */
    @Override
    public String createOrder( MultipartFile[] files, AcceptOrder acceptOrder ) throws IOException {
        //获取禅道session,每次刷新登录
        String zentaosid = loginZenTao();
        //禅道任务id
        String id = null;
        //获取文件map
        Map fileMap = getFilesObject(files);
        //拼装请求参数
        RequestBody body = packageCreateOrderObject(acceptOrder, fileMap);
        //拼接创建工单地址参数
        String createUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_POST_CREATE_ORDER_URL, acceptOrder.getProjectCode(), zentaosid);//项目id
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(createUrl);
        zenTaoClientVo.setBody(body);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_POST_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_ADD.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            //成功
            //判断是否有失败请求
            if ("fail".equals(jsonObject.getString("result"))) {
                JSONObject messageObj = jsonObject.getJSONObject("message");
                messageObj.forEach(( key, value ) -> {
                    log.warn("错误值{},原因{}", key, value.toString());
                    //超时处理
                    if (value.toString().contains("timeout")) {
                        //删除缓存
                        redisUtil.hdel(getZenTaoKey());
                    }
                });
                throw new BaseException("新增禅道工单失败");
            }
            id = jsonObject.getString("id");
        }
        log.info("禅道id=" + zentaosid);
        return id;
    }

    /**
     * @param
     * @return
     * @description: 给工单添加备注
     * @author hyh
     * @date 2022/7/13 14:10
     */
    @Override
    public Boolean addComment( AcceptOrderRemark acceptOrderRemark ) throws IOException {
        Boolean isSuccess = false;
        //获取禅道session,每次刷新登录
        String zentaosid = loginZenTao();
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("comment", acceptOrderRemark.getContext()).build();
        //拼接增加工单评论url
        String addCommentUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_POST_ADD_ORDER_COMMENT_URL, acceptOrderRemark.getSourceOrderNum(), zentaosid);
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(addCommentUrl);
        zenTaoClientVo.setBody(body);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_POST_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_ADD_COMMENT.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            //成功
            isSuccess = true;
        }
        return isSuccess;
    }


    /**
     * @param
     * @return
     * @description: 关闭工单,并添加备注
     * @author hyh
     * @date 2022/7/13 13:34
     */
    @Override
    public Boolean closeOrder( AcceptOrderRemark orderRemark ) throws IOException {
        Boolean isSuccess = false;
        //获取禅道session,每次刷新登录
        String zentaosid = loginZenTao();
        //拼接关闭工单地址参数
        String closeUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_POST_CLOSE_ORDER_URL, orderRemark.getSourceOrderNum(), zentaosid);
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("comment", orderRemark.getContext()).addFormDataPart("status", ZenTaoTaskStatusEnum.ZEN_TAO_TASK_STATUS_CLOSE.getCode()).addFormDataPart("deadline", orderRemark.getDeadline()) //必传 预计结束日期
                .build();
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(closeUrl);
        zenTaoClientVo.setBody(body);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_POST_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_CLOSE.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
//            String tmp = StringEscapeUtils.unescapeEcmaScript(jsonObject.getString("data"));
//            JSONObject object = JSONObject.parseObject(tmp);
            //成功
            isSuccess = true;
        }
        return isSuccess;
    }

    /**
     * @param ids
     * @return
     * @description: 批量关闭工单
     * @author hyh
     * @date 2022/7/13 13:34
     */
    @Override
    public Boolean closeBatchOrder( String ids ) throws IOException {
        Boolean isSuccess = false;
        //获取禅道session,每次刷新登录
        String zentaosid = loginZenTao();
        //拼接关闭工单地址参数
        String closeUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_GET_CLOSE_BATCH_ORDER_URL, ids, zentaosid);
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(closeUrl);
        zenTaoClientVo.setBody(null);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_GET_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_BATCH_CLOSE.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            //成功
            isSuccess = true;
        }
        return isSuccess;
    }

    /**
     * @param
     * @return
     * @description: 删除工单
     * @author hyh
     * @date 2022/7/13 13:34
     */
    @Override
    public Boolean delOrder( AcceptOrder acceptOrder ) throws IOException {
        Boolean isSuccess = false;
        //获取禅道session,每次刷新登录
        String zentaosid = loginZenTao();
        //拼接删除工单地址参数
        String delUrl = MessageFormat.format(ZenTaoConstants.ZENTAO_GET_DELETE_ORDER_URL, acceptOrder.getProjectCode(), acceptOrder.getSourceOrderNum(), zentaosid);
        //拼装请求客户端参数
        ZenTaoClientVo zenTaoClientVo = new ZenTaoClientVo();
        zenTaoClientVo.setZenTaoUrl(delUrl);
        zenTaoClientVo.setBody(null);
        zenTaoClientVo.setMethodType(ZenTaoConstants.HTTP_GET_METHOD);
        zenTaoClientVo.setOption(ZenTaoOptionEnum.ZEN_TAO_OPTION_DEL.getInfo());
        JSONObject jsonObject = packageZenTaoHttpClient(zenTaoClientVo);
        if (ObjectUtils.isNotEmpty(jsonObject)) {
            //成功
            isSuccess = true;
        }
        return isSuccess;
    }

    /**
     * @param
     * @return String zentaosid
     * @description: 获取zentaosid
     * @author hyh
     * @date 2022/7/13 17:24
     */
    private String getZentaoSid() throws IOException {
        String zentaosid = null;
        String zentaoKey = getZenTaoKey();
        //判断缓存值是否存在
        if (ObjectUtils.isEmpty(redisUtil.get(zentaoKey))) {
            zentaosid = getZenTaoSession();
        } else {
            zentaosid = redisUtil.get(zentaoKey).toString();
        }
        if (StringUtils.isEmpty(zentaosid)) {
            log.warn("禅道获取zentaosid失败");
            throw new BaseException("禅道获取zentaosid失败");
        }
        return zentaosid;
    }

    /**
     * @param
     * @return
     * @description: 获取 ZenTaoKey
     * @author hyh
     * @date 2022/7/14 9:01
     */
    private String getZenTaoKey() {
        // 获取当前登录用户
        SysUser userCurrent = userUtil.getCurrentUser();
        if (ObjectUtils.isEmpty(userCurrent)) {
            log.warn("获取当前登录用户失败");
            throw new BaseException("获取当前登录用户失败");
        }
        return Constant.PREFIX_ZENTAO_SESSION + userCurrent.getId();
    }

    /**
     * @param
     * @return
     * @description: 获取 登录人信息
     * @author hyh
     * @date 2022/7/14 9:01
     */
    private SysUser getLoginUserInfo() {
        // 获取当前登录用户
        SysUser userCurrent = userUtil.getCurrentUser();
        if (ObjectUtils.isEmpty(userCurrent)) {
            log.warn("获取当前登录用户失败");
            throw new BaseException("获取当前登录用户失败");
        }
        return userCurrent;
    }

    /**
     * @param
     * @return
     * @description: 封装禅道创建工单请求体
     * @author hyh
     * @date 2022/7/14 9:17
     */
    private RequestBody packageCreateOrderObject( AcceptOrder acceptOrder, Map fileMap ) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        builder.addFormDataPart("execution", acceptOrder.getProjectCode())                           //必传   项目id
                .addFormDataPart("type", getZnTaoDataByData("taskType", acceptOrder.getZenTaoType()))                                   //必传   任务类型
                .addFormDataPart("assignedTo[]", acceptOrder.getAssignedTo())                           //必传   指派给谁,必传
                .addFormDataPart("status", ZenTaoTaskStatusEnum.ZEN_TAO_TASK_STATUS_DOING.getCode())    //后台必传 任务状态
                .addFormDataPart("name", acceptOrder.getTaskName())                                     //必传   任务名称,
                .addFormDataPart("pri", getZnTaoDataByData("pri", acceptOrder.getPri()))                                           //必传   任务优先级,1-4,最高,较高,一般,最低
                .addFormDataPart("estimate", acceptOrder.getAssessTime().toString())                    //必传   预计工时
                .addFormDataPart("desc", acceptOrder.getAcceptContext())                                //必传 任务描述
                .addFormDataPart("estStarted", acceptOrder.getCreateTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")))                  //必传 预计开始日期
                .addFormDataPart("deadline", acceptOrder.getDeadline().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));                     //必传 预计结束日期
//                .addFormDataPart("story", "")                                                               //非必传 关联需求
//                .addFormDataPart("color", "")                                                               //非必传  标题颜色
//                .addFormDataPart("module", "")                                                              //非必传  所属模块

        //添加文件
        if (CollectionUtils.isNotEmpty(fileMap)) {
            for (Map.Entry entry : fileMap.entrySet()) {
                builder.addFormDataPart("files[]", entry.getValue(), RequestBody.create(MediaType.parse("application/octet-stream"), multipartFileToFile(entry.getKey())))//非必传 附件
                        .addFormDataPart("labels[]", entry.getValue());               //非必传 附件名称;
            }
        }
        RequestBody body = builder.build();
        return body;
    }

    /**
     * @param type 字典类型 dataId 字典值id
     * @return String
     * @description: 根据字典类型字典值id获取所需字段
     * @author hyh
     * @date 2022/7/28 9:58
     */
    private String getZnTaoDataByData( String type, String dataId ) {
        String code = "";
        SDictData data = sDictDataMapper.selectById(dataId);
        if (ObjectUtils.isNotEmpty(data)) {
            if ("pri".equals(type)) {
                code = data.getSort().toString();
            }
            if ("taskType".equals(type)) {
                code = data.getDataCode();
            }
        }
        return code;
    }

    /**
     * @param
     * @return
     * @description: 根据文件查询文件绝对地址和名称并返回
     * @author hyh
     * @date 2022/7/14 10:35
     */
    private Map getFilesObject( MultipartFile[] files ) {
        Map map = new HashMap<>(1 << 4);
        if (files.length > 0) {
            for (MultipartFile file : files) {
                if (file.isEmpty()) {
                    throw new BaseException("文件不存在");
                }
                //文件名称
                String fileName = file.getOriginalFilename();
                //保存平台工单信息
                map.put(file, fileName);
            }
        }
        return map;
    }


    /**
     * MultipartFile 转 File
     *
     * @param multipartFile
     * @throws Exception
     */
    public static File multipartFileToFile( MultipartFile multipartFile ) {

        File file = null;
        //判断是否为null
        if (multipartFile.equals("") || multipartFile.getSize() <= 0) {
            return file;
        }
        //MultipartFile转换为File
        InputStream ins = null;
        OutputStream os = null;
        try {
            ins = multipartFile.getInputStream();
            file = new File(multipartFile.getOriginalFilename());
            os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return file;
    }


    /**
     * @param zenTaoClientVo
     * @return
     * @description: 封装禅道请求客户端
     * @author hyh
     * @date 2022/7/20 17:25
     */
    private JSONObject packageZenTaoHttpClient( ZenTaoClientVo zenTaoClientVo ) {
        Response response = null;
        JSONObject jsonObject = new JSONObject();
        try {
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("text/plain");
            //拼接增加工单评论url
            Request request = new Request.Builder()
                    .url(zenTaoClientVo.getZenTaoUrl())
                    .method(zenTaoClientVo.getMethodType(), zenTaoClientVo.getBody())
                    .build();
            response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                String res = response.body().string();
                if (isJSON2(res)) {
                    jsonObject = JSONObject.parseObject(res);
                } else {
                    jsonObject.put("flag", true);
                }
            }
        } catch (SocketTimeoutException e) {
            // 超时
            log.error("executeHttpRequest TimeOut, e: " + e);
            throw new BaseException("禅道" + zenTaoClientVo.getOption() + "超时");
        } catch (IOException e) {
            // 网络IO异常
            log.error("executeHttpRequest IOException, e: " + e);
            throw new BaseException("禅道" + zenTaoClientVo.getOption() + "网络IO异常");
        } catch (Exception e) {
            // 其他异常
            log.error("禅道" + zenTaoClientVo.getOption() + "失败");
            throw new BaseException("禅道" + zenTaoClientVo.getOption() + "失败");
        } finally {
            if (response != null) {
                // body 必须被关闭,否则会发生资源泄漏;
                response.body().close();
            }
        }
        return jsonObject;
    }

    /**
     * @param str
     * @return boolean
     * @description: 判断是否是json格式
     * @author hyh
     * @date 2022/7/21 15:21
     */
    public static boolean isJSON2( String str ) {
        boolean result = false;
        try {
            Object obj = JSON.parse(str);
            result = true;
        } catch (Exception e) {
            result = false;
        }
        return result;
    }
}

4.傻瓜式调用

你可能感兴趣的:(JAVA,java,json)