Java新程北斗

新程北斗API:**
https://www.gzxcbd.cn/808gps/open/webApi.html#sec-vehicle-device-track**
获取设备历史轨迹:
必填参数:汽车设备号id,开始时间,结束时间
时间格式:yyyy-MM-dd HH:mm:ss

控制层:
 HashMap<String, Object> data = new HashMap<>();
        //获取轨迹
        List<BeiDouTrack> trackList = new ArrayList<>();
        if (StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime)) {
            try {
                String did = beidouApi.getHandler().getDidByVehicle(plate).get(0);
                data.put("did", did);
                trackList = beidouApi.getHandler().getTrackListByDid(did, startTime, endTime);
            } catch (Exception e) {

                br.setCode(ResultCodeEnum.HTTP_ERROR.getCode());
                br.setMsg("定位系统不存在该车辆信息,请更换车牌号");
                return br;
            }
        }
        data.put("orderId", orderId);
        data.put("type", type);
        data.put("plate", plate);
        data.put("points", trackList);
        br.setData(data);
        return br;

北斗API

package com.taiji.web.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.taiji.core.util.HttpClient;
import com.taiji.dto.*;
import com.taiji.web.config.BeiDouConfig;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 新程北斗API
 *
 * @author liping
 * @date 2024-09-06 15:31
 **/
@Service
public class BeidouApi {

    /**
     * 获取用户车辆信息API地址
     */
    private static final String API_QUERY_USER_VEHICLE = "https://www.gzxcbd.cn/StandardApiAction_queryUserVehicle.action";

    /**
     * 获取车辆最新位置信息API地址
     */
    private static final String API_VEHICLE_STATUS = "https://www.gzxcbd.cn/StandardApiAction_vehicleStatus.action";

    /**
     * 获取车辆设备号API地址
     */
    private static final String API_GET_DEVICE_BY_VEHICLE = "https://www.gzxcbd.cn/StandardApiAction_getDeviceByVehicle.action";


    /**
     * 获取设备在线状态API地址
     */
    private static final String API_GET_DEVICE_OL_STATUS = "https://www.gzxcbd.cn/StandardApiAction_getDeviceOlStatus.action";

    /**
     * 录像查询API地址
     */
    private static final String API_GET_VIDEO_FILE_INFO = "https://www.gzxcbd.cn/StandardApiAction_getVideoFileInfo.action";

    /**
     * 获取设备历史轨迹API地址
     */
    private static final String API_QUERY_TRACK_DETAIL = "https://www.gzxcbd.cn/StandardApiAction_queryTrackDetail.action";

    /**
     * 获取车辆行驶里程API地址
     */
    private static final String API_RUN_MILEAGE = "https://www.gzxcbd.cn/StandardApiAction_runMileage.action";

    /**
     * 获取设备报警数据(分页)API地址
     */
    private static final String API_QUERY_ALARM_DETAIL = "https://www.gzxcbd.cn/StandardApiAction_queryAlarmDetail.action";

    /**
     * 获取设备状态(定位状态)API地址
     */
    private static final String API_GET_DEVICE_STATUS = "https://www.gzxcbd.cn/StandardApiAction_getDeviceStatus.action";

    /**
     * 会话号参数名
     */
    private static final String PARAM_JSESSION = "jsession";

    /**
     * 返回码字段名
     */
    private static final String RESULT_FIELD = "result";

    /**
     * 错误消息字段名
     */
    private static final String MESSAGE_FIELD = "message";

    /**
     * 成功返回码
     */
    private static final int SUCCESS_RESULT = 0;

    @Resource
    private BeiDouConfig beiDouConfig;

    private final Map<String, BeidouApiHandler> HANDLER_MAP = new HashMap<>();


    public BeidouApiHandler getHandler(String username, String password){
        BeidouApiHandler handler = HANDLER_MAP.get(username);
        if(handler == null){
            handler = new BeidouApiHandler(username, password, beiDouConfig);
            HANDLER_MAP.put(username, handler);
        }
        return handler;
    }

    public BeidouApiHandler getHandler(){
        return getHandler(beiDouConfig.getUsername(), beiDouConfig.getPassword());
    }


    public static class BeidouApiHandler{

        private final String username;

        private final String password;

        private final BeiDouConfig beiDouConfig;



        public BeidouApiHandler(String username, String password, BeiDouConfig beiDouConfig){
            this.username = username;
            this.password = password;
            this.beiDouConfig = beiDouConfig;
        }

        /**
         * 获取会话号
         * @return
         */
        public String getSession(){
            return beiDouConfig.getSession(this.username, this.password);
        }

        /**
         * 添加会话号到请求参数
         * @return
         */
        private Map<String, String> withSession(){
            String session = getSession();
            Map<String, String> data = new HashMap<>(1);
            data.put(PARAM_JSESSION, session);
            return data;
        }

        /**
         * 添加会话号到请求参数
         * @param data  请求参数
         * @return
         */
        private Map<String, String> withSession(Map<String, String> data){
            data.putAll(withSession());
            return data;
        }

        /**
         * 返回码校验
         * @param json  响应报文
         */
        private void checkResult(JSONObject json){
            if(json.getIntValue(RESULT_FIELD) != SUCCESS_RESULT){
                throw new BeidouApiException(json.getIntValue(RESULT_FIELD), json.getString(MESSAGE_FIELD));
            }
        }



        /**
         * 获取用户车辆信息
         * @return
         */
        public JSONObject queryUserVehicle(){
            String result = HttpClient.doPost(API_QUERY_USER_VEHICLE, withSession());
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);
            return json;
        }




        /**
         * 获取车牌号列表
         * @return
         */
        public List<String> getPlateList(){
            JSONObject vehicleRes = queryUserVehicle();
            JSONArray vehicles = vehicleRes.getJSONArray("vehicles");
            if(CollectionUtils.isNotEmpty(vehicles)){
                return vehicles.stream().map(o -> ((JSONObject)o).getString("nm")).collect(Collectors.toList());
            }
            return null;
        }

        /**
         * 获取车牌号(多个车牌号以“,”拼接)
         * @return
         */
        public String getPlates(){
            JSONObject vehicleRes = queryUserVehicle();
            JSONArray vehicles = vehicleRes.getJSONArray("vehicles");
            if(CollectionUtils.isNotEmpty(vehicles)){
                return vehicles.stream().map(o -> ((JSONObject)o).getString("nm")).collect(Collectors.joining(","));
            }
            return "";
        }

        /**
         * 获取车辆最新位置信息
         * @param plates    车牌号码(多个办车牌以“,”拼接)
         * @return
         */
        public List<BeiDouLocationInfor> getLocations(String plates){
            Map<String, String> data = new HashMap<>(3);
            data.put("vehiIdno", plates);
            data.put("toMap", "2");
            String res = HttpClient.doPost(API_VEHICLE_STATUS, withSession(data));
            JSONObject json = JSONObject.parseObject(res);
            checkResult(json);
            return JSON.parseArray(json.getString("infos"), BeiDouLocationInfor.class);
        }

        /**
         * 获取车辆最新位置信息
         * @param plates    车牌号码列表
         * @return
         */
        public List<BeiDouLocationInfor> getLocations(List<String> plates){
            return getLocations(join(plates));
        }

        /**
         * 获取车辆最新位置信息
         * @param plates    车牌号码列表
         * @return
         */
        public List<CarDtoForDispatch> vehicleStatus(List<String> plates){
            return vehicleStatus(join(plates));
        }

        /**
         * 获取车辆最新位置信息
         * @param plates    车牌号码(多个办车牌以“,”拼接)
         * @return
         */
        public List<CarDtoForDispatch> vehicleStatus(String plates){
            List<BeiDouLocationInfor> locations = getLocations(plates);
            if(CollectionUtils.isNotEmpty(locations)){
                return locations.stream().map(o -> {
                    CarDtoForDispatch carDto = new CarDtoForDispatch();
                    carDto.setPlate(o.getVi());
                    carDto.setMlat(o.getMlat()); //纬度
                    carDto.setMlng(o.getMlng()); //经度
                    carDto.setTm(o.getTm()); //时间
                    return carDto;
                }).collect(Collectors.toList());
            }
            return null;
        }

        /**
         * 获取车辆设备号
         * @param plates  车牌号 可以是多个,以','分割
         * @return
         */
        public JSONObject getDeviceByVehicle(String plates){
            Map<String, String> data = new HashMap<>(2);
            data.put("vehiIdno", plates);
            String res = HttpClient.doPost(API_GET_DEVICE_BY_VEHICLE, withSession(data));
            JSONObject json = JSONObject.parseObject(res);
            checkResult(json);
            return json;
        }

        /**
         * 获取车辆设备号
         * @param plates  车牌号列表
         * @return
         */
        public JSONObject getDeviceByVehicle(List<String> plates){
            return getDeviceByVehicle(join(plates));
        }

        /**
         * 获取车辆设备号
         * @param plates    车牌号 可以是多个,以','分割
         * @return
         */
        public List<String> getDidByVehicle(String plates){
            JSONObject json = getDeviceByVehicle(plates);
            JSONArray devices = json.getJSONArray("devices");
            if(CollectionUtils.isNotEmpty(devices)){
                return devices.stream().map(o -> ((JSONObject) o).getString("did")).collect(Collectors.toList());
            }
            return null;
        }

        /**
         * 获取车辆设备号
         * @param plates    车牌号列表
         * @return
         */
        public List<String> getDidByVehicle(List<String> plates){
            return getDidByVehicle(join(plates));
        }

        /**
         * 获取设备在线状态
         * @param plates    车牌号 可以是多个,以','分割
         * @return
         */
        public JSONObject getDeviceOlStatus(String plates){
            Map<String, String> data = new HashMap<>(2);
            data.put("vehiIdno", plates);
            String result = HttpClient.doPost(API_GET_DEVICE_OL_STATUS, withSession(data));
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);
            return json;
        }

        /**
         * 获取设备在线状态
         * @param plates    车牌号列表
         * @return
         */
        public JSONObject getDeviceOlStatus(List<String> plates){
            return getDeviceOlStatus(join(plates));
        }

        /**
         * 获取设备在线状态
         * @param plates    车牌号 可以是多个,以','分割
         * @return
         */
        public List<BeiDouOnLine> getDeviceOnLine(String plates){
            JSONObject json = getDeviceOlStatus(plates);
            return JSON.parseArray(json.getString("onlines"), BeiDouOnLine.class);
        }

        /**
         * 获取设备在线状态
         * @param plates    车牌号列表
         * @return
         */
        public List<BeiDouOnLine> getDeviceOnLine(List<String> plates){
            return getDeviceOnLine(join(plates));
        }


        /**
         * 录像查询 (原始接口返回json)
         * @param plate     车牌号
         * @param year      年份
         * @param month     月份
         * @param day       日期
         * @param type      录像类型 0表示常规,1表示报警,-1表示所有
         * @param fileType  文件类型 1表示图像 2表示录像。
         * @return
         */
        public JSONObject getVideoFileInfo(String plate,String year,String month,String day,String type,String fileType){
            String did = getDidByVehicle(plate).get(0);
            Map<String, String> data = new HashMap<>(16);
            data.put("DevIDNO", did);
            data.put("LOC", "1");
            data.put("CHN", "0");
            data.put("YEAR", year);
            data.put("MON", month);
            data.put("DAY", day);
            data.put("RECTYPE", type);
            data.put("FILEATTR", fileType);
            data.put("BEG", "0");
            data.put("END", "86399");
            data.put("ARM1", "0");
            data.put("ARM2", "0");
            data.put("RES", "0");
            data.put("STREAM", "0");
            data.put("STORE", "0");

            String result = HttpClient.doPost(API_GET_VIDEO_FILE_INFO, withSession(data));
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);

            return json;
        }

        /**
         * 录像查询(返回文件列表)
         * @param plate     车牌号
         * @param year      年份
         * @param month     月份
         * @param day       日期
         * @param type      录像类型 0表示常规,1表示报警,-1表示所有
         * @param fileType  文件类型 1表示图像 2表示录像。
         * @return
         */
        public JSONArray getVideoFiles(String plate,String year,String month,String day,String type,String fileType){
            JSONObject json = getVideoFileInfo(plate, year, month, day, type, fileType);
            return json.getJSONArray("files");
        }

        /**
         * 获取设备历史轨迹
         * @param plate     车牌号
         * @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss)
         * @param endTime   结束时间(格式:yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public JSONObject queryTrackDetail(String plate,String startTime,String endTime){
            String did = getDidByVehicle(plate).get(0);
            return queryTrackDetailByDid(did, startTime, endTime);
        }

        /**
         * 根据设备号获取设备历史轨迹
         * @param did       设备号
         * @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss)
         * @param endTime   结束时间(格式:yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public JSONObject queryTrackDetailByDid(String did,String startTime,String endTime){
            Map<String, String> data = new HashMap<>(5);
            data.put("devIdno", did);
            data.put("begintime", startTime);
            data.put("endtime", endTime);
            data.put("toMap", "2");

            String result = HttpClient.doPost(API_QUERY_TRACK_DETAIL, withSession(data));
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);
            return json;
        }

        /**
         * 获取设备历史轨迹
         * @param plate     车牌号
         * @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss)
         * @param endTime   结束时间(格式:yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public List<BeiDouTrack> getTrackList(String plate,String startTime,String endTime){
            JSONObject json = queryTrackDetail(plate, startTime, endTime);
            return JSON.parseArray(json.getString("tracks"), BeiDouTrack.class);
        }

        /**
         * 获取设备历史轨迹
         * @param did       设备号
         * @param startTime 开始时间(格式:yyyy-MM-dd HH:mm:ss)
         * @param endTime   结束时间(格式:yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public List<BeiDouTrack> getTrackListByDid(String did,String startTime,String endTime){
            JSONObject json = queryTrackDetailByDid(did, startTime, endTime);
            return JSON.parseArray(json.getString("tracks"), BeiDouTrack.class);
        }


        /**
         * 获取车辆行驶里程
         * @param plates    车牌号 可以是多个,以','分割
         * @param beginTime 开始时间 开始时间不得大于结束时间(格式:yyyy-MM-dd)
         * @param endTime   结束时间(格式:yyyy-MM-dd)
         * @return
         */
        public JSONObject runMileage(String plates, String beginTime, String endTime){
            Map<String, String> data = new HashMap<>(4);
            data.put("vehiIdno", plates);
            data.put("begintime", beginTime);
            data.put("endtime", endTime);

            String result = HttpClient.doPost(API_RUN_MILEAGE, withSession(data));
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);
            return json;
        }

        /**
         * 获取车辆行驶里程
         * @param plates    车牌号列表
         * @param beginTime 开始时间 开始时间不得大于结束时间(格式:yyyy-MM-dd)
         * @param endTime   结束时间(格式:yyyy-MM-dd)
         * @return
         */
        public JSONObject runMileage(List<String> plates, String beginTime, String endTime){
            return runMileage(join(plates), beginTime, endTime);
        }

        /**
         * 获取车辆行驶里程
         * @param plates    车牌号 可以是多个,以','分割
         * @param beginTime 开始时间 开始时间不得大于结束时间(格式:yyyy-MM-dd)
         * @param endTime   结束时间(格式:yyyy-MM-dd)
         * @return
         */
        public List<BeiMileageDto> getMileageList(String plates, String beginTime, String endTime){
            JSONObject json = runMileage(plates, beginTime, endTime);
            return JSON.parseArray(json.getString("infos"), BeiMileageDto.class);
        }

        /**
         * 获取车辆行驶里程
         * @param plates    车牌号列表
         * @param beginTime 开始时间 开始时间不得大于结束时间(格式:yyyy-MM-dd)
         * @param endTime   结束时间(格式:yyyy-MM-dd)
         * @return
         */
        public List<BeiMileageDto> getMileageList(List<String> plates, String beginTime, String endTime){
            return getMileageList(join(plates), beginTime, endTime);
        }


        /**
         * 获取车辆载重告警
         * @param plates    车牌号 可以是多个,以','分割
         * @param beginTime 开始时间 (格式:yyyy-MM-dd HH:mm:ss)
         * @param endTime   结束时间 开始时间不得大于结束时间,并且查询天数不得大于90天(格式:yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public JSONArray getLoadAlarm(String plates,String beginTime,String endTime){
            Map<String, String> data = new HashMap<>(9);
            data.put("vehiIdno", plates);
            data.put("begintime", beginTime);
            data.put("endtime", endTime);
            data.put("armType", "1325,1324");
            data.put("handle", "0");
            data.put("currentPage", "1");
            data.put("pageRecords", "10000");
            data.put("toMap", "2");

            String result = HttpClient.doPost(API_QUERY_ALARM_DETAIL, withSession(data));
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);
            return json.getJSONArray("alarms");
        }

        /**
         * 获取车辆载重告警
         * @param plates    车牌号列表
         * @param beginTime 开始时间 (格式:yyyy-MM-dd HH:mm:ss)
         * @param endTime   结束时间 开始时间不得大于结束时间,并且查询天数不得大于90天(格式:yyyy-MM-dd HH:mm:ss)
         * @return
         */
        public JSONArray getLoadAlarm(List<String> plates,String beginTime,String endTime){
            return getLoadAlarm(join(plates), beginTime, endTime);
        }


        /**
         * 获取设备状态(定位状态)
         * @param plates 车牌号 可以是多个,以','分割
         * @return
         */
        public List<BeiDouDeviceStatus> getDeviceStatus(String plates){
            //https://www.gzxcbd.cn/StandardApiAction_getDeviceStatus.action?jsession=jsessionStr
            // &vehiIdno=vehiIdnoStr
            // &geoaddress=1
            // &language=zh
            // &toMap=2
            Map<String, String> data = new HashMap<>(5);
            data.put("vehiIdno", plates);
            data.put("geoaddress", "1");
            data.put("language", "zh");
            data.put("toMap", "2");

            String result = HttpClient.doPost(API_GET_DEVICE_STATUS, withSession(data));
            JSONObject json = JSONObject.parseObject(result);
            checkResult(json);
            JSONArray status = json.getJSONArray("status");
            if(CollectionUtils.isNotEmpty(status)){
                return status.stream().map(BeidouApiHandler::convert).collect(Collectors.toList());
            }
            return null;
        }

        /**
         * json转设备状态对象
         * @param object    json对象
         * @return
         */
        private static BeiDouDeviceStatus convert(Object object){
            JSONObject json = (JSONObject) object;
            BeiDouDeviceStatus status = new BeiDouDeviceStatus();
            // 车牌号
            status.setPlate(json.getString("vid"));
            // 经过转换后的经度
            status.setMlng(json.getString("mlng"));
            // 经过转换后的纬度
            status.setMlat(json.getString("mlat"));
            // 位置上报时间
            status.setGt(StringUtils.replace(json.getString("gt"), ".0", ""));
            // 速度(方向)
            Double spValue = json.getDouble("sp");
            String direction = getDirection(json.getInteger("hx"));
            if(spValue != null){
                StringBuilder builder = new StringBuilder().append(spValue / 10.0).append("公里/时");
                if(direction != null){
                    builder.append("(").append(direction).append(")");
                }
                status.setSp(builder.toString());
            }
            // 高程
            String gd = json.getString("gd");
            if(null != gd) {
                status.setGd(gd + "(m)");
            }
            // 行驶记录仪速度
            Double tspValue = json.getDouble("tsp");
            if (null != tspValue) {
                status.setTsp(tspValue / 10.0 + "公里/时");
            }
            // 里程
            Double lcValue = json.getDouble("lc");
            if (null != lcValue) {
                status.setTsp(lcValue / 1000 + "公里");
            }
            // 今日里程
            Double bsd1Value = json.getDouble("bsd1");
            if (null != bsd1Value) {
                status.setTsp(bsd1Value / 10.0 + "公里");
            }
            // 设备号
            status.setId(json.getString("id"));
            // 位置
            status.setPs(json.getString("ps"));
            // 在线状态
            status.setOnlineStatus(StringUtils.equals("1", json.getString("ol")) ? "在线" : "离线");
            // 网络类型
            status.setNet(getNet(json.getInteger("net")));
            // 状态1
            status.setS1(getS1(json.getInteger("s1")));
            // 卫星数
            status.setSn(json.getInteger("sn"));

            // 状态汇总信息
            List<String> olItems = Arrays.asList(status.getOnlineStatus(), status.getNet(), status.getS1(), status.getSn() == null ? null : "卫星数:" + status.getSn());
            status.setOl(join(olItems));
            return status;
        }

        /**
         * 获取方向
         * @param hx
         * @return
         */
        private static String getDirection(Integer hx){
            if(hx == null){
                return null;
            }
            Integer direction = ((hx + 22) / 45) & 0x7;
            String[] directionNames = {"北","东北","东","东南","南","西南","西","西北"};
            if(direction >= 0 && direction < directionNames.length){
                return directionNames[direction];
            }
            return null;
        }

        /**
         * 获取网络类型
         * @param net
         * @return
         */
        private static String getNet(Integer net){
            if(net == null){
                return null;
            }
            String[] netNames = {"3G","WIFI","有线","4G","5G"};
            if(net >= 0 && net < netNames.length){
                return netNames[net];
            }
            return null;
        }

        /**
         * 获取状态1
         * @param s1
         * @return
         */
        private static String getS1(Integer s1){
            if(s1 == null){
                return null;
            }
            List<String> items = new ArrayList<>();
            items.add(getStatusType(s1, 2) ? "ACC开启" : "ACC关闭");
            if(getStatusType(s1, 14)){
                items.add("怠速");
            }
            if(getStatusType(s1, 15)){
                items.add("行驶");
            }
            if(getStatusType(s1, 17)){
                items.add("怠速");
            }
            return join(items);
        }

        private static boolean getStatusType(int num, int index) {
            return (num >> (index - 1) & 1) == 1;
        }

        /**
         * 字符串拼接
         * @param collection    集合
         * @param delimiter     分隔符
         * @return
         */
        private static String join(Collection<String> collection, CharSequence delimiter){
            if(CollectionUtils.isNotEmpty(collection)){
                return collection.stream().filter(StringUtils::isNotEmpty).collect(Collectors.joining(delimiter));
            }
            return "";
        }

        /**
         * 字符串拼接(以”,“为分隔符)
         * @param collection    集合
         * @return
         */
        private static String join(Collection<String> collection){
            return join(collection, ",");
        }
    }

}

post请求

package com.taiji.core.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import java.util.Map;

public class HttpClient {

    static final Logger logger = LoggerFactory.getLogger(HttpClient.class);

    public static String doGet(String url) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            // 通过址默认配置创建一个httpClient实例
            httpClient = HttpClients.createDefault();
            // 创建httpGet远程连接实例
            HttpGet httpGet = new HttpGet(url);
            // 设置配置请求参数
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(35000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(35000)// 请求超时时间
                    .setSocketTimeout(60000)// 数据读取超时时间
                    .build();
            // 为httpGet实例设置配置
            httpGet.setConfig(requestConfig);
            // 执行get请求得到返回对象
            response = httpClient.execute(httpGet);
            // 通过返回对象获取返回数据
            HttpEntity entity = response.getEntity();
            // 通过EntityUtils中的toString方法将结果转换为字符串
            result = EntityUtils.toString(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static String doPost(String url, Map<String, String> map) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        String result = "";
        try {
            httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(120000)// 连接主机服务超时时间
                    .setConnectionRequestTimeout(120000)// 请求超时时间
                    .setSocketTimeout(120000)// 数据读取超时时间
                    .build();
            httpPost.setConfig(requestConfig);

            ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
            if (null != map && !map.isEmpty()) {
                map.forEach((key, value) -> {
                    if(StringUtils.isNotBlank(value)){
                        parameters.add(new BasicNameValuePair(key, value));
                    }

                });
            }
            httpPost.setEntity(new UrlEncodedFormEntity(parameters,"UTF-8"));
            logger.info("发送请求时间:[{}]", DateUtils.getCurrentYYYYMMDDHHmmss());
            response = httpClient.execute(httpPost);
            logger.info("返回请求时间:[{}]", DateUtils.getCurrentYYYYMMDDHHmmss());
            HttpEntity entity = response.getEntity();
            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            logger.info("异常请求时间:[{}]", DateUtils.getCurrentYYYYMMDDHHmmss());
            logger.error("发送请求失败:", e);
            throw new RuntimeException("请求异常:", e);
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    logger.error("关闭连接失败:", e);
                }
            }
            if (null != httpClient) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    logger.error("关闭连接失败:", e);
                }
            }
        }
        return result;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值