RestTemplate exchange

@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;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值