java里面封装https请求工具类

1.工具类如下

java 复制代码
@Component
@Slf4j
public class RestClientUtil<T> {

    private final RestTemplate restTemplate;

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

    public JSONObject uploadFile(String url, String fileUrl) throws IOException {
        List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
        messageConverters.add(new MappingJackson2HttpMessageConverter());
        messageConverters.add(new FormHttpMessageConverter());
        messageConverters.add(new FastJsonHttpMessageConverter());
        restTemplate.setMessageConverters(messageConverters);

        // 构建请求体
        MultipartBodyBuilder bodyBuilder = new MultipartBodyBuilder();
        File file = new File(fileUrl);
        Path filePath = Paths.get(file.getAbsolutePath());
        byte[] fileBytes = Files.readAllBytes(filePath);
        bodyBuilder.part("data", new ByteArrayResource(fileBytes) {
            @Override
            public String getFilename() {
                return file.getName();
            }
        }, MediaType.MULTIPART_FORM_DATA);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        HttpEntity<MultiValueMap<String, HttpEntity<?>>> requestEntity = new HttpEntity<>(bodyBuilder.build(), headers);

        // 发送请求并处理响应
        ResponseEntity<JSONObject> exchange = restTemplate.exchange(url, HttpMethod.POST, requestEntity, JSONObject.class);
        if (exchange.getStatusCode() == HttpStatus.OK) {
            return exchange.getBody();
        }
        return null;
    }

    public ResponseEntity<T> get(String url, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        return restTemplate.exchange(url, HttpMethod.GET, requestEntity, responseType);
    }


    public <T> T post(String url, MultiValueMap<String, String> requestBody, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(requestBody, headers);
        ResponseEntity<T> responseEntity = restTemplate.postForEntity(
                url,
                requestEntity,
                responseType
        );
        return responseEntity.getBody();
    }

    public ResponseEntity<T> delete(String url, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();

        HttpEntity<String> requestEntity = new HttpEntity<>(headers);

        return restTemplate.exchange(url, HttpMethod.DELETE, requestEntity, responseType);
    }

    public ResponseEntity<T> put(String url, Object body, Class<T> responseType) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Object> requestEntity = new HttpEntity<>(body, headers);

        return restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType);
    }
}

2.调用

java 复制代码
@org.springframework.stereotype.Service
@Service(version = "1.0.0")
@Slf4j
public class OcrServiceImpl implements OcrService {

@Resource
    private RedissonClient redissonClient;

    @Autowired
    private RestClientUtil<JSONObject> restClientUtil;


public BaseResponseVo<String> getLicenseInfo(OcrDTO ocrDTO) throws IOException {
JSONObject imgResult = restClientUtil.uploadFile(imgUrl + "?appkey=" + keyMapping.get(ocrDTO.getOcrType()), imagePath);

MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
            paramsMap.set("key", keyMapping.get(ocrDTO.getOcrType()));
            paramsMap.set("imageId", imgResult.getString("data"));
            JSONObject resultData = restClientUtil.post(url + typeMapping.get(ocrDTO.getOcrType()), paramsMap, JSONObject.class);
            if (!"10000".equals(resultData.getString("code"))) {
                return BaseResponseVo.error(imgResult.getString("code"), imgResult.getString("message"));
            }

}


}
相关推荐
侧耳倾听11135 分钟前
单元测试之mockito
java·单元测试
苹果酱056739 分钟前
SpringCloud第二篇:注册中心Eureka
java·vue.js·spring boot·mysql·课程设计
圈圈编码40 分钟前
WebSocket
java·网络·spring boot·websocket·网络协议·spring
szuaudi42 分钟前
SpringMVC实现text/event-stream(SSE)
java·spring
nlog3n1 小时前
Java 桥接模式 详解
java·开发语言·桥接模式
理想奋斗中1 小时前
【并发编程 | 第五篇】探索ThreadLocal的原理
java·多线程·threadlocal·threadlocalmap
李小白661 小时前
JavaEE初阶复习(JVM篇)
java·jvm·java-ee
Easonmax1 小时前
【JavaEE】网络原理详解
java·java-ee
java_学习爱好者2 小时前
SpringBoot配置文件多环境开发
java
别来无恙✲2 小时前
SpringBoot启动方法分析
java·springboot·场景设计