HttpUtil.java 14.7 KB
package com.sincere.haikangface.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sincere.haikangface.bean.face.PermissionBean;
import com.sincere.haikangface.bean.face.PermissionDHBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * http 工具类
 */
@Slf4j
public class HttpUtil {

    public static String post(String requestUrl, String accessToken, String params)
            throws Exception {
        String contentType = "application/json";
        return HttpUtil.post(requestUrl, accessToken, contentType, params);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params)
            throws Exception {
        String encoding = "UTF-8";
        if (requestUrl.contains("nlp")) {
            encoding = "GBK";
        }
        return HttpUtil.post(requestUrl, accessToken, contentType, params, encoding);
    }

    public static String post(String requestUrl, String accessToken, String contentType, String params, String encoding)
            throws Exception {
        String url = requestUrl + "?access_token=" + accessToken;
        return HttpUtil.postGeneralUrl(url, contentType, params, encoding);
    }

    public static String postGeneralUrl(String generalUrl, String contentType, String params, String encoding)
            throws Exception {
        URL url = new URL(generalUrl);
        // 打开和URL之间的连接
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        // 设置通用的请求属性
        connection.setRequestProperty("Content-Type", contentType);
        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // 得到请求的输出流对象
        DataOutputStream out = new DataOutputStream(connection.getOutputStream());
        out.write(params.getBytes(encoding));
        out.flush();
        out.close();

        // 建立实际的连接
        connection.connect();
        // 获取所有响应头字段
        Map<String, List<String>> headers = connection.getHeaderFields();
        // 遍历所有的响应头字段
        for (String key : headers.keySet()) {
            System.err.println(key + "--->" + headers.get(key));
        }
        // 定义 BufferedReader输入流来读取URL的响应
        BufferedReader in = null;
        in = new BufferedReader(
                new InputStreamReader(connection.getInputStream(), encoding));
        String result = "";
        String getLine;
        while ((getLine = in.readLine()) != null) {
            result += getLine;
        }
        in.close();
        System.err.println("result:" + result);
        return result;
    }

    /**
     * 下发人脸值253服务设备
     * @param filePath
     * @param card
     * @param name
     * @param deviceId
     * @param startTime
     * @param endTime
     * @param validTimeEnabled
     * @param userType
     */
    public static void uploadImgs(String filePath, String card, String name, String deviceId, String startTime,
                                     String endTime, int validTimeEnabled, String userType,Integer schoolId) {
        if (!new File(filePath).exists()) {
            log.error("图片不存在,图片路径:{}",filePath);
            return;
        }
        try{
            String url = "http://120.26.116.253:8089/file/uploadImg";
//            String url = "http://127.0.0.1:8089/file/uploadImg";
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
            headers.setContentType(mediaType);
            MultiValueMap<String, Object> multivaluedMap = new LinkedMultiValueMap<>();
            FileSystemResource fileSystemResource = new FileSystemResource(filePath);
            multivaluedMap.add("file", fileSystemResource);
            multivaluedMap.add("deviceId", deviceId);
            multivaluedMap.add("card", card);
            multivaluedMap.add("name", name);
            multivaluedMap.add("startTime", startTime);
            multivaluedMap.add("endTime", endTime);
            multivaluedMap.add("validTimeEnabled", validTimeEnabled);
            multivaluedMap.add("userType", userType);
            multivaluedMap.add("schoolId", schoolId);
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multivaluedMap, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            log.info("发送请求,下发人脸至253服务器海康设备,请求地址:{} ,下发用户名:{},返回信息:{}",url,name,responseEntity.getBody());
        }catch (Exception e){
            log.error("发送请求,下发人脸至253服务器海康设备,发生异常: {}",e);
        }
    }


    public static boolean IsDeviceOnline(String deviceId) {
        String url = "http://120.26.116.253:8089/file/IsDeviceOnline?deviceId=" + deviceId;
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.getForObject(url, String.class);
        return res.equals("1");
    }

    /**
     * 删除海康设备卡信息
     * @param deviceId
     * @param card
     * @return
     */
    public static boolean deleteCard(String deviceId, String card) {
        String url = "http://120.26.116.253:8089/file/DeleteCard?deviceId=" + deviceId + "&card=" + card;
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.getForObject(url, String.class);
        return res.equals("1");
    }

    /**
     * 获取海康设备卡信息
     * @param deviceId
     * @param card
     * @return
     */
    public static boolean getCard(String deviceId, String card) {
        String url = "http://120.26.116.253:8089/file/getCard?deviceId=" + deviceId + "&card=" + card;
        RestTemplate restTemplate = new RestTemplate();
        String res = restTemplate.getForObject(url,String.class);
        return res.equals("1");
    }

    /**
     * 下发权限至海康设备
     * @param permissionBean
     */
    public static void sendPermission2HK(PermissionBean permissionBean) {
        try {
            String url = "http://120.26.116.253:8089/file/sendPermiss";
            if (null != permissionBean) {
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                MediaType mediaType = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE);
                headers.setContentType(mediaType);
                HttpEntity<PermissionBean> httpEntity = new HttpEntity<>(permissionBean, headers);
                ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
                String reqJson= JSON.toJSONString(permissionBean);
                log.info("发送请求,下发权限至海康设备,请求地址:{},请求参数:{},返回信息:{}",url,reqJson,responseEntity.getBody());
            }
        } catch (Exception e) {
            log.error("发送请求,下发权限至海康设备,发生异常: {}",e);
        }
    }

    /**
     * 百度人脸识别查询
     * @param file
     * @param schoolId
     * @return
     */
    public static JSONObject sendToKB(File file,String schoolId) {
        String url = "http://120.26.116.253:9214/baiduapi/search/" + schoolId;
        MultiValueMap<String, Object> multivaluedMap = new LinkedMultiValueMap<>();
        HttpHeaders headers = new HttpHeaders();
        RestTemplate restTemplate = new RestTemplate();
        try {
            MediaType mediaType = MediaType.parseMediaType(MediaType.MULTIPART_FORM_DATA_VALUE);
            headers.setContentType(mediaType);
            FileSystemResource fileSystemResource = new FileSystemResource(file);
            multivaluedMap.add("file", fileSystemResource);
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(multivaluedMap, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
            log.info("发送请求,人脸识别查询,请求地址:{},返回信息:{}",url,jsonObject.toJSONString());
            return  jsonObject;
        } catch (Exception e) {
            log.info("发送请求,百度人脸识别失败,异常信息:{}",e);
        }
        return null;
    }

    /**
     * 下发单个人脸至大华设备
     * @param filePath
     * @param schoolId
     * @param studentCode
     * @param clintType
     * @param deviceId
     * @return
     */
    public static void uploadDHImgForOne(String filePath,Integer schoolId,String studentCode,int clintType,String deviceId) {
        String api = "http://114.55.30.100:8991/user/uploadImgAndUserInfo";
        try {
            String url = String.format(api +"?schoolId=%s&studentCode=%s&deviceId=%s&clint_type=%s&file=%s",schoolId,studentCode,deviceId,clintType,filePath);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            log.info("发送请求,下发单个人脸至大华设备,请求地址:{} ,返回信息:{}",url, responseEntity.getBody());
        } catch (Exception e) {
            log.error("发送请求,下发单个人脸至大华,异常信息: {}",e);
        }
    }

    /**
     * 下发权限至大华设备
     * @param permissionBean
     * @return
     */
    public static void sendDHPermission(PermissionDHBean permissionBean) {
        try{
            String url = "http://121.40.109.21:8991/file/sendPermission";
//            String url = "http://127.0.0.1:8991/file/sendPermission";
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            MediaType mediaType = MediaType.parseMediaType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            headers.setContentType(mediaType);
            HttpEntity<PermissionDHBean> httpEntity = new HttpEntity<>(permissionBean, headers);
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
            log.info("发送请求,下发权限至大华设备,请求地址:{} ,返回信息:{}",url, responseEntity.getBody());
        }catch (Exception e){
            log.error("发送请求,下发权限至大华设备,异常信息,{}",e);
        }
    }

    /**
     * 照片下发,发送海康设备
     * @param schoolId
     * @param userType
     * @param deviceIds
     */
    public static void uploadHkImg( String schoolId,int userType,String deviceIds) {
        String api = "http://114.55.30.100:8089/facereco/sendFaces";
        try {
            String url = String.format(api +"?schoolId=%s&userType=%s&deviceIds=%s",schoolId,userType,deviceIds);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            log.info("发送请求,照片下发至海康设备,请求地址:{},返回信息: {}",url,responseEntity.getBody());
        } catch (Exception e) {
            log.error("发送请求,照片下发至海康设备,异常信息:{}",e);
        }
    }

    /**
     * 照片下发,发送大华设备
     * @param schoolId
     * @param userType
     * @param deviceIds
     */
    public static void uploadDHImg(String schoolId,Integer userType,String deviceIds,Integer studentType,String sex) {
        String api = "http://114.55.30.100:8991/operate/sendUserFaces";
//        String api = "http://127.0.0.1:8991/user/sendFaces";
        try {
            String url = String.format(api +"?schoolId=%s&userType=%s&deviceIds=%s&studentType=%s&sex=%s",schoolId,userType,deviceIds,studentType,sex);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            log.info("发送请求,照片下发至大华设备,请求地址:{},返回信息: {}",url,responseEntity.getBody());
        } catch (Exception e) {
            log.error("发送请求,照片下发至大华设备,异常信息:{}",e);
        }
    }

    /**
     * 删除大华设备人脸
     * @param schoolId
     * @param cardNum
     * @param deviceId
     */
    public static void deleteDHFace(Integer schoolId,String cardNum,String deviceId) {
        String api = "http://121.40.109.21:8991/operate/deleteFaceByCard";
        try {
            String url = String.format(api +"?schoolId=%s&cardNum=%s&deviceId=%s",schoolId,cardNum,deviceId);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            log.info("发送请求,删除大华设备人脸,请求地址:{},返回信息: {}",url,responseEntity.getBody());
        } catch (Exception e) {
            log.error("发送请求,删除大华设备人脸,异常信息:{}",e);
        }
    }

    /**
     * 在线活体检测
     * @param checkUrl
     * @return
     */
    public static String checkFace(String checkUrl) {
        String api = "http://114.55.30.100:8991/user/checkFace";
        try {
            String url = String.format(api +"?url=%s",checkUrl);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
            log.info("发送请求,删除大华设备人脸,请求地址:{},返回信息: {}",url,responseEntity.getBody());
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("发送请求,删除大华设备人脸,异常信息:{}",e);
        }
        return null;
    }
}