Spring Boot 整合RestTemplate,传输Map。
map必须为MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();否则会报错。
图片传输需要进行Base64进行转换,防止图片超过2M从而传输失败
话不多说,直接上接口代码:
@RequestMapping("/list")
@ResponseBody
public String PostForPic() {
String url = "http://192.168.110.100:8001/getForPic";
String path = this.getClass().getResource("/").getPath();
String ImagePath = path + "static/test1.jpg";
String base64 = convertFileToBase64(ImagePath);
RestTemplate rest = new RestTemplate();
MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
headers.add("content-type", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
// headers.add("Accept", MediaType.APPLICATION_FORM_URLENCODED_VALUE);
// 请求体
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("file", "picture");
body.add("base64", base64);
body.add("key", "123456");
HttpEntity<MultiValueMap<String, String>> httpEntity = new HttpEntity<>(body, headers);
ResponseEntity<String> response = rest.postForEntity(url, httpEntity, String.class);
String res = response.getBody();
return res;
}
convertFileToBase64转换方法 :
值得注意的是,笔者推荐用 apache的 Base64来编码和解码:
import org.apache.commons.codec.binary.Base64;
如果没有这个包,添加如下依赖即可。
<dependency>
<groupId>commons-codec</groupId><artifactId>commons-codec</artifactId>
<version>1.14</version></dependency>
public String convertFileToBase64(String imgPath) {
InputStream in = null;
byte[] data = null;
// 读取图片字节数组
try {
in = new FileInputStream(imgPath);
System.out.println("文件大小(字节)=" + in.available());
data = new byte[in.available()];
in.read(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
// 对字节数组进行 Base64编码,得到 Base64编码的字符串
String base64Str = Base64.encodeBase64String(data);
return base64Str;
}
接收Post请求:
//接受Post发送的pic并存入本地static
@RequestMapping("/getForPic")
@ResponseBody
public void getPic(@RequestParam Map<String,String> map) {
System.out.println("map"+map);
String base64 = map.get("base64");
byte[] bytes = Base64.decodeBase64(base64); // Base64解码
// 使用 SpringBoot自带的 ClassUtils获取项目的根路径
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
FileOutputStream fis = null;
try {
fis = new FileOutputStream(path + "static/postFormData.jpg");
fis.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
通过PostMan发送请求,查看本地路径检查图片是否成功传输:
检查发现图片已成功存入,大功告成。