RestTemplate的基本使用之postForObject()
1. post请求的基本调用
原始接口(生产者)
package com.zk.datastruct.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RequestMapping("/producer")
@RestController
@CrossOrigin
public class ProducerController {
@PostMapping("/execute")
public JSONObject execute(@RequestBody Map<String, String> map) {
// 处理正常业务代码
return new JSONObject();
}
}
调用接口(消费者)
package com.zk.datastruct.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
@RequestMapping("/consumer")
@RestController
@CrossOrigin
public class ConsumerController {
@PostMapping("/invokeExecute")
public JSONObject invokeExecute(){
// 获取RestTemplate对象
RestTemplate restTemplate = new RestTemplate();
// 设置请求头,请求类型为json
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 设置请求参数
HashMap<String, Object> map = new HashMap<>();
map.put("username", "zhangsan");
//用HttpEntity封装整个请求报文
HttpEntity<HashMap<String, Object>> request = new HttpEntity<>(map, headers);
// 开始调用
// 参数1:目标请求地址
// 参数2:请求体
// 参数3:目标请求接口的返回值类型(execute接口的返回值类型)
JSONObject result = restTemplate.postForObject("http://192.168.12.12:8080/test/producer/execute", request, JSONObject.class);
return result;
}
}
2. 文件类型的调用方式
原始接口(生产者)
package com.zk.datastruct.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RequestMapping("/producer")
@RestController
@CrossOrigin
public class ProducerController {
@PostMapping("/upload")
public JSONObject upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
// 处理文件上传业务代码
return new JSONObject();
}
}
调用接口(消费者)
package com.zk.datastruct.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.util.HashMap;
@RequestMapping("/consumer")
@RestController
@CrossOrigin
public class ConsumerController {
@PostMapping("/invokeUpload")
public JSONObject invokeUpload(){
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
File file = new File("/Users/zk/Downloads/readme.txt");
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("file", new FileSystemResource(file));
form.add("filename",file.getName());
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
JSONObject result = restTemplate.postForObject("http://192.168.12.12:8080/test/producer/upload", files, JSONObject.class);
return result;
}
}
3. 代码优化
在一个成熟的项目中,其中RestTemplate对象和HttpHeaders对象就不应该再new出来了,应使用spring工厂自动创建,使用时注入即可。包括目标URL,也不应该硬编码在程序中写死,应写在application.yml配置文件中,用到时取出即可,这样也方便进行管理和调试。
applicationi.yml配置文件
rest-template:
upload-url: http://192.168.12.12:8080/test/producer/upload
execute-url: http://192.168.12.12:8080/test/producer/execute
创建配置类
@Component
public class RestTemplateConfig {
@Bean
RestTemplate getRestTemplate(){
return new RestTemplate();
}
@Bean
HttpHeaders getHttpHeaders(){
return new HttpHeaders();
}
}
修改控制器类
package com.zk.datastruct.controller;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import java.io.File;
import java.util.HashMap;
@RequestMapping("/consumer")
@RestController
@CrossOrigin
public class ConsumerController {
@Value("${rest-template.upload-url}")
private String uploadUrl;
@Value("${rest-template.execute-url}")
private String executeUrl;
@Autowired
private RestTemplate restTemplate;
@Autowired
private HttpHeaders headers;
@PostMapping("/invokeExecute")
public JSONObject invokeExecute(){
// 设置请求头,请求类型为json
headers.setContentType(MediaType.APPLICATION_JSON);
// 设置请求参数
HashMap<String, Object> map = new HashMap<>();
map.put("username", "zhangsan");
//用HttpEntity封装整个请求报文
HttpEntity<HashMap<String, Object>> request = new HttpEntity<>(map, headers);
// 开始调用
// 参数1:目标请求地址
// 参数2:请求体
// 参数3:目标请求接口的返回值类型(execute接口的返回值类型)
JSONObject result = restTemplate.postForObject(executeUrl, request, JSONObject.class);
return result;
}
@PostMapping("/invokeUpload")
public JSONObject invokeUpload(){
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
File file = new File("/Users/zk/Downloads/readme.txt");
MultiValueMap<String, Object> form = new LinkedMultiValueMap<>();
form.add("file", new FileSystemResource(file));
form.add("filename",file.getName());
HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(form, headers);
JSONObject result = restTemplate.postForObject(uploadUrl, files, JSONObject.class);
return result;
}
}
本文详细介绍了如何使用Spring框架中的RestTemplate发起POST请求,包括普通数据类型和文件类型的请求方式,并提供了代码优化建议。
581

被折叠的 条评论
为什么被折叠?



