RestTemplate 的用法

1.引入对应依赖

2.private final RestTemplate restTemplate;

3.上代码

@Service
@Slf4j
public class CspWarehouseServiceImpl implements ICspWarehouseService {
private final RestTemplate restTemplate;

    public CspWarehouseServiceImpl() {
        this.restTemplate = new RestTemplate();
    }

private final String returnMessage = "无数据,参数都正确,没有数据";


 /**
     * 仓库温度gps请求
     *
     * @param url              url
     * @param gpsReqDTO        请求采纳数
     * @param responseBodyType json类型
     * @param <T>              参数
     * @return 结果
     */
    public <T> T exchange(String url,
                          String gpsReqDTO,
                          Class<T> responseBodyType) {
        try {
            log.info("请求仓库温度gps接口请求报文={}", gpsReqDTO);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(gpsReqDTO, headers);
            ResponseEntity<T> responseEntity = restTemplate.postForEntity(
                    url,
                    requestEntity,
                    responseBodyType
            );
            return responseEntity.getBody();
        } catch (Exception e) {
            log.error("调用仓库温度GPS接口异常=", e);
            return null;
        }
    }

}
public List<CspWarehouseEquipment> selectCspWarehouseEquipmentList(CspWarehouseEquipment cspWarehouseEquipment) {

CspGPSReqDTO gpsReqDTO = buildGpsRequest(equipmentNumberList, "GetColdStorageCurrentTemp", startTime, endTime);

String reqDto = objectMapper.writeValueAsString(gpsReqDTO);
            String url = environment.getProperty("gps.platform.coldTmpUrl");

JSONObject returnObjDevice = exchange(url, reqDto, JSONObject.class);

if (returnObjDevice != null && (!returnMessage.contains(returnObjDevice.getString("Rtn_Data"))
                    && !"[]".equals(returnObjDevice.getString("Rtn_Data")) &&
                    !returnMessage.contains(returnObjDevice.getString("Rtn_Msg")))) {
                Integer rtnCode = returnObjDevice.getInteger("Rtn_Code");
                if (rtnCode != null && rtnCode == 0) {
                    if (!"无数据!".equals(returnObjDevice
                            .getString("Rtn_Data"))) {
                        List<CspWarehouseTempInterface> temperatureDetailsList = JSON.parseObject(returnObjDevice
                                        .getString("Rtn_Data"),
                                new TypeReference<List<CspWarehouseTempInterface>>() {
                                });
                        structureData(list, temperatureDetailsList);
                    }
                }
            }
}

你可能感兴趣的:(java)