RestTemplate exchange

陆昂然
2023-12-01
@GetMapping("/putByText")
@ApiOperation(value = "远程更新资源", position = 1, httpMethod = "GET", response = Result.class)
public Result putByText(@ApiParam(value = "text参数", name = "text") @RequestParam(name = "text") String text){
    MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
    map.add("text", text);
    JSONObject jsonObject = new RestTemplateUtil().putSend(restTemplate,"url", map);
    return Result.build(jsonObject);
}


@PostMapping("/postUploadFile")
@ApiOperation(value = "远程上传文件", position = 1, httpMethod = "POST", response = Result.class)
public String postUploadFile(MultipartFile file) throws IOException {
    MultiValueMap<String, Object> bodyParams = new LinkedMultiValueMap<>();
    org.springframework.core.io.Resource resource = new ByteArrayResource(file.getBytes()){
        @Override
        public String getFilename() {
            return file.getOriginalFilename();
        }
    };
    bodyParams.add("file", resource);
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(bodyParams, headers);
    String result= restTemplate.postForObject("url", requestEntity, String.class);
    return result;
}

工具类

package cn.piesat.ias.util;

import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.net.URI;

public class RestTemplateUtil {

    private static final Logger log = LoggerFactory.getLogger(RestTemplateUtil.class);

    /**
     *  rest api 发送消息
     * @param apiUrl  请求地址
     * @param map
     * @return
     */
    public JSONObject putSend(RestTemplate restTemplate ,String apiUrl, MultiValueMap<String, String> map) {
        JSONObject jsonObject = new JSONObject();
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
//            List<MediaType> acceptableMediaTypes = new ArrayList<>();
//            acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
//            acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
            HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = restTemplate.exchange(new URI(apiUrl), HttpMethod.PUT, httpEntity,String.class);
            String result = response.getBody();
            jsonObject = JSONObject.parseObject(result);
            jsonObject.put("responseCode","200");
        }catch (Exception e){
            jsonObject.put("responseCode","500");
            log.error("调用restTemplate.exchange()"+e);
        }
        return jsonObject;
    }

    /**
     *  rest api 发送消息
     * @param apiUrl  请求地址
     * @param map
     * @return
     */
    public String exchange(RestTemplate restTemplate ,String apiUrl,HttpMethod method ,MultiValueMap<String, Object> map) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
            ResponseEntity<String> response = restTemplate.exchange(new URI(apiUrl), method, httpEntity,String.class);
            String result = response.getBody();
            return result;
        }catch (Exception e){
            log.error("调用restTemplate.exchange()"+e);
        }
        return null;
    }
    /**
     *  rest api 发送消息
     * @param apiUrl  请求地址
     * @param map
     * @param
     * @return
     */
    public String exchange(RestTemplate restTemplate, String apiUrl, HttpMethod method, MultiValueMap<String, Object> map, String sign) {
        try {
            //复杂构造函数的使用
            SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
            requestFactory.setConnectTimeout(100000);// 设置超时
            requestFactory.setReadTimeout(100000);
            RestTemplate  restTemplate = new RestTemplate(requestFactory);
            HttpHeaders headers = new HttpHeaders();
            ResponseEntity<String> response = null;
            //根据自己需要定义对应的ContentType
            if(sign.equals("form_data")){
                headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            }else if(sign.equals("json")){
                headers.setContentType(MediaType.APPLICATION_JSON);
            }
            HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(map, headers);
            response = restTemplate.exchange(new URI(apiUrl), method, httpEntity,String.class);
            String result = response.getBody();
            return result;
        }catch (Exception e){
            log.error("调用restTemplate.exchange()"+e);
        }
        return null;
    }
}

 类似资料:

相关阅读

相关文章

相关问答