yinyitong-zhongyuyuan-dll-s.../src/main/java/com/dpkj/common/utils/ThirdService.java

90 lines
3.3 KiB
Java
Raw Normal View History

package com.dpkj.common.utils;
2025-02-08 15:40:47 +08:00
import com.alibaba.fastjson.JSON;
import com.dpkj.common.dto.LexMarkDTO;
import com.dpkj.common.dto.LexMarkResultDTO;
import com.dpkj.common.exception.RRException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
2025-02-08 15:40:47 +08:00
/**
* 第三方服务主要是调用打印机等
*
* @author <a href="https://gitee.com/shi-chongli">石头人</a>
* @version 1.0
* @since 2025-02-08 10:45:01
*/
@Slf4j
@Component
public class ThirdService {
@Value("${app.custom.lexMarkServiceIp}")
private String lexMarkServiceIp;
@Value("${app.custom.lexMarkServicePort}")
private String lexMarkServicePort;
/**
* 利盟台式机-立体机 接口请求
* @param lexMarkDTO 请求DTO
* @return result
*/
public LexMarkResultDTO callDevice(LexMarkDTO lexMarkDTO) {
try {
URL url = new URL(lexMarkServiceIp + ":" + lexMarkServicePort + "/CallDevice");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
2025-02-08 15:40:47 +08:00
connection.setRequestProperty("Content-Type", "application/json");
// 将LexMarkDTO对象转换为JSON字符串
2025-02-08 15:40:47 +08:00
String jsonInputString = JSON.toJSONString(lexMarkDTO);
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
wr.write(input, 0, input.length);
2025-02-08 15:40:47 +08:00
log.info(jsonInputString);
}
int responseCode = connection.getResponseCode();
if (responseCode!= HttpURLConnection.HTTP_OK) {
log.error("利盟服务请求失败,响应码:{},请求参数:{}", responseCode, lexMarkDTO);
throw new RRException("利盟服务请求失败,响应码:" + responseCode);
}
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine())!= null) {
response.append(inputLine);
}
in.close();
// 将响应JSON字符串转换为LexMarkResultDTO对象
2025-02-08 15:40:47 +08:00
LexMarkResultDTO lexMarkResultDTO = JSON.parseObject(response.toString(), LexMarkResultDTO.class);
if( lexMarkResultDTO.getResult() != 0){
log.error("利盟服务请求出错:{}", lexMarkResultDTO);
throw new RRException(lexMarkResultDTO.toString());
}
return lexMarkResultDTO;
}catch (Exception e){
log.error("利盟服务请求失败:{}", lexMarkDTO, e);
2025-02-08 15:40:47 +08:00
if ( e instanceof RRException ){
throw new RRException(((RRException) e).getCode(), e.getMessage());
}
throw new RRException("利盟服务请求失败");
}
}
}