@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 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 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> 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);
public JSonObject putSend(RestTemplate restTemplate ,String apiUrl, MultiValueMap map) {
JSonObject jsonObject = new JSonObject();
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
// List acceptableMediaTypes = new ArrayList<>();
// acceptableMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
// acceptableMediaTypes.add(MediaType.APPLICATION_PROBLEM_JSON_UTF8);
HttpEntity> httpEntity = new HttpEntity<>(map, headers);
ResponseEntity 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;
}
public String exchange(RestTemplate restTemplate ,String apiUrl,HttpMethod method ,MultiValueMap map) {
try {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity> httpEntity = new HttpEntity<>(map, headers);
ResponseEntity 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;
}
}



