前言:
本文用到两个第三方包,分别是 apache 的 Base64 和阿里的 fastjson ,依赖如下:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
正文:
SpringBoot项目发送GET、POST请求,可以使用RestTemplate来完成,简便好用。
一、初始化RestTemplate
@Component
public class MyConfig {
@Autowired
RestTemplateBuilder templateBuilder;
@Bean
public RestTemplate restTemplate() {
return templateBuilder.build();
}
}
二、发送、接收GET请求
2.1、RestTemplate发送GET请求:
@RestController
@RequestMapping("/")
public class TestController {
private static Logger log = LoggerFactory.getLogger(this.getClass());
// GET方式调用远程服务接口,传参 K=V 形式,url拼接
@RequestMapping("/get")
public String sendRemoteByGet(String name, String age) {
log.info("-------- sendGet: 进入 sendRemoteByGet() --------");
log.info("-------- sendGet: name:{},age:{} --------", name, age);
StringBuilder urlBuilder = new StringBuilder(getUrl);
urlBuilder.append("?&name=" + name);
urlBuilder.append("&age=" + age);
String url = urlBuilder.toString();
/*
// 发送GET请求
ResponseEntity<String> entity = restTemplate.getForEntity(url, String.class);
String body = entity.getBody();
System.out.println(body);
return body;
*/
// 发送GET请求
String response = restTemplate.getForObject(url, String.class);
return response;
}
}
2.2、接收GET请求:
// 接收远程GET调用
@RequestMapping("/receivedGet")
public String receivedGet(@RequestParam(defaultValue = "nobody") String name, @RequestParam(defaultValue = "empty") String age) {
log.info("======== receivedGet: 进入 receivedGet() ========");
log.info("======== receivedGet: name:{},age:{}========", name, age);
if (name.equals("null")) {
name = "nobody";
}
if (age.equals("null")) {
age = "empty";
}
if (!name.equals("nobody") || !age.equals("empty")) {
return "已收到信息。name:" + name + ",age:" + age;
}
return "未收到信息。name:" + name + ",age:" + age;
}
三、发送、接收POST请求
- 场景:假设在项目的 resources/static/ 目录下有一张 .jpg 的图片,我们需要用POST方式将图片发送给对方
- 思路:读取图片,将图片用Base64编码,然后以POST方式发送请求
在发送POST请求的时候,有可能会因为请求体太大而报错,SpringBoot项目默认的请求体大小最大为2M,如果出现请求体过大而报错的情况,我们只需要在 application.properties 配置文件中更改一个配置项:
#设置post请求体大小,其默认是2M,-1表示无限制
server.tomcat.max-http-form-post-size=-1
首先需要一个成员方法,将图片转换成Base64字符串:
// 本地文件(图片、excel等)转换成 Base64字符串
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);
/*
值得注意的是,笔者推荐用 apache的 Base64来编码和解码:import org.apache.commons.codec.binary.Base64;
如果没有这个包,添加如下依赖即可。
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.14</version>
</dependency>
*/
return base64Str;
}
3.1、发送POST请求,参数为json格式:
// POST方式调用远程服务接口,传参:json格式
@RequestMapping("/json")
public String sendPostJson() {
// 获取项目根路径
String path = this.getClass().getResource("/").getPath();
//System.out.println("path=" + path ); // path=/D:/Project/http/target/classes/
String imagePath = path + "static/RE4wEr6_1920x1080.jpg";
System.out.println("imagePath=" + imagePath);
String base64 = convertFileToBase64(imagePath);
// System.out.println(base64);
// 请求体
JSONObject jsonObject = new JSONObject(); // HashMap
// JSONObject jsonObject = new JSONObject(true); // LinkedHashMap
jsonObject.put("file", "picture");
jsonObject.put("base64", base64);
jsonObject.put("key", "123456");
// 请求头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
// jsonObject.toString() = jsonObject.toJSONString(); 二者就是同一个方法
HttpEntity<String> httpEntity = new HttpEntity<>(jsonObject.toString(), headers);
// 假设规定的返回类型为 String类型
ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, httpEntity, String.class);
String body = responseEntity.getBody();
System.out.println("body=" + body);
// Object object = JSONObject.parse(body); // 接收对象应指定具体类型,用 JavaBean来接收
// JSONObject resJsonObject = JSONObject.parseObject(body); // 实质上是转换成 Map
return body;
}
3.2、接收POST请求的json数据:
// 接收参数:json格式
@RequestMapping("/receivedPostJson")
public String receivedPostJson(@RequestBody JSONObject jsonObject) {
System.out.println("jsonObject=" + jsonObject);
// JSONObject jsonObject = new JSONObject(); // HashMap
// JSONObject jsonObject = new JSONObject(true); // LinkedHashMap
Set<Map.Entry<String, Object>> entries = jsonObject.entrySet();
for (Map.Entry<String, Object> entry : entries) {
String key = entry.getKey();
String value = (String) entry.getValue();
System.out.println("key=" + key + " " + "value=" + value);
}
String base64 = (String) jsonObject.get("base64");
byte[] bytes = Base64.decodeBase64(base64); // Base64解码
String path = this.getClass().getResource("/").getPath();
FileOutputStream fis = null;
try {
fis = new FileOutputStream(path + "static/postJson.jpg");
fis.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String jsonString = JSONObject.toJSONString(jsonObject);
return jsonString;
}
3.3、发送POST请求,参数为FromData格式,即 K=V:
// POST方式调用远程接口,传参:formData格式
@RequestMapping("/data")
public String sendPostFormData() {
// 获取项目根路径
String path = this.getClass().getClassLoader().getResource("");
String imagePath = path + "static/RE4wEr6_1920x1080.jpg";
String base64 = convertFileToBase64(imagePath);
// 请求头
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> entity = restTemplate.postForEntity(url, httpEntity, String.class);
String code = entity.getStatusCode().toString();
String response = entity.getBody();
System.out.println("code=" + code + ",resp=" + response);
return response;
}
3.4、接收POST请求的FormData数据:
// 接收参数:formData格式
@RequestMapping("/receivedPostFormData")
public String receivedPost(@RequestParam Map<String, String> map) {
System.out.println("map=" + map);
/*
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
System.out.println("key=" + key + " " + "value=" + value);
}
*/
Set<String> keySet = map.keySet();
for (String key : keySet) {
String value = map.get(key);
System.out.println("key=" + key + " " + "value=" + value);
}
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();
}
}
}
String jsonString = JSONObject.toJSONString(map);
return jsonString;
}