SpringBoot之RestTemplate上传文件

@Resource(name = "restTemplate")
private RestTemplate restTemplate;

private JSONObject upload(String url) throws Exception {

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    
    MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
    FileSystemResource fileSystemResource = new FileSystemResource(url);
    parts.add("file", fileSystemResource);
    parts.add("param", "参数");
    HttpEntity<MultiValueMap<String, Object>> entity = new HttpEntity<>(parts, headers);
    ResponseEntity<JSONObject> exchange = null;
    exchange = restTemplate.exchange(apiUrl, HttpMethod.valueOf("POST"), entity, JSONObject.class);
    if (exchange.getStatusCode().isError()) {
        log.error("the rest api request failed");
    }
    
    JSONObject body = exchange.getBody();
    log.info("upload attach success response:" + body);
    
    return body;
}
@Configuration
public class RestClientConfig {

    @Bean("restTemplate")
    public RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(30000);// 设置连接超时,单位毫秒
        requestFactory.setReadTimeout(30000);  //设置读取超时
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setRequestFactory(requestFactory);
        //这个是处理接口返回TEXT_HTML无法解析问题
        restTemplate.getMessageConverters().add(new CustomMappingJackson2HttpMessageConverter());
        return restTemplate;
    }
    
}
public class CustomMappingJackson2HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    //这个是处理接口返回TEXT_HTML无法解析问题
    public CustomMappingJackson2HttpMessageConverter(){
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);
        setSupportedMediaTypes(mediaTypes);
    }

}

你可能感兴趣的:(Windows,Linux,java,spring,boot,restful)