//url为请求路径,params为参数map
public static String sendPostRequest(String url, MultiValueMap<String, String> params){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
// 以表单的方式提交
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
//将请求头部和参数合成一个请求
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
try {
//忽略https证书请求
SslUtils.ignoreSsl();
} catch (Exception e) {
e.printStackTrace();
}
//执行HTTP请求
return restTemplate.postForEntity(url, request, String.class).getBody();
}
上传文件时需转换file
File file=new File("C:\\Users\\Administrator\\Desktop\\cloud\\test.xlsx");
FileInputStream fileInputStream=new FileInputStream(file);
//构建请求体
CommonInputStreamResource commonInputStreamResource = null;
try {
commonInputStreamResource = new CommonInputStreamResource(fileInputStream,file.length(),file.getName());
} catch (Exception e) {
e.printStackTrace();
}
package cn.gov.ahsz.sys.index;
import org.springframework.core.io.InputStreamResource;
import java.io.InputStream;
public class CommonInputStreamResource extends InputStreamResource {
private long length;
private String fileName;
public CommonInputStreamResource(InputStream inputStream, long length, String fileName) {
super(inputStream);
this.length = length;
this.fileName = fileName;
}
/**
* 覆写父类方法
* 如果不重写这个方法,并且文件有一定大小,那么服务端会出现异常
* {@code The multi-part request contained parameter data (excluding uploaded files) that exceeded}
*/
@Override
public String getFilename() {
return fileName;
}
/**
* 覆写父类 contentLength 方法
* 因为 {@link org.springframework.core.io.AbstractResource#contentLength()}方法会重新读取一遍文件,
* 而上传文件时,restTemplate 会通过这个方法获取大小。然后当真正需要读取内容的时候,发现已经读完,会报如下错误。
*/
@Override
public long contentLength() {
long estimate = length;
return estimate == 0 ? 1 : estimate;
}
public void setLength(long length) {
this.length = length;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}