二、将RestTemplate加入spring管理org.springframework.boot spring-boot-starter-weborg.projectlombok lomboktrue org.springframework.boot spring-boot-starter-testtest com.alibaba.fastjson2 fastjson22.0.3.android
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
@Configuration
public class BeanConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
RestTemplate restTemplate = new RestTemplate(factory);
return restTemplate;
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
//建⽴连接所⽤的时间,适⽤于⽹络状况正常的情况下,两端连接所⽤的时间。单位毫秒
factory.setConnectTimeout(15000);
//建⽴连接后从服务器读取到可⽤资源所⽤的时间。单位毫秒
factory.setReadTimeout(5000);
return factory;
}
}
三、请求基础数据
server.port=8089
import lombok.Data;
@Data
public class Student {
private String name;
private Integer age;
}
import lombok.Data;
@Data
public class Teacher {
private String name;
private String phone;
}
准备两个请求,一个get一个post
#get地址 http://localhost:8089/test/getTeacherByStudnetId #post地址 http://localhost:8089/test/saveStudent http://localhost:8089/test/saveStudent2
import com.minos.resttemplete.bean.Student;
import com.minos.resttemplete.bean.Teacher;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/test")
public class TestController {
@GetMapping("/getTeacherByStudnetId")
public Teacher getTeacher(Long studentId) {
System.out.println("根据学生:" + studentId + "查询老师");
Teacher teacher = new Teacher();
teacher.setName("xxx老师");
teacher.setPhone("13113113152");
return teacher;
}
@PostMapping("/saveStudent")
public Student addStudnet(Student student) {
System.out.println(student.toString());
return student;
}
@PostMapping("/saveStudent2")
public Student addStudnet2(@RequestBody Student student) {
System.out.println(student.toString());
return student;
}
}
四、RestTemplate之get请求
1、getForObject
@Autowired
RestTemplate restTemplate;
@Test
void testGetForObject() {
String url = "http://localhost:8089/test/getTeacherByStudnetId";
Map paramMap = new HashMap<>();
paramMap.put("studentId", 5L);
//只能返回响应体
Teacher teacher = restTemplate.getForObject(url, Teacher.class, paramMap);
System.out.println(JSON.toJSONString(teacher));
// {"name":"xxx老师","phone":"13113113152"}
}
2、 getForEntity
@Autowired
RestTemplate restTemplate;
@Test
void testGetForEntity() {
String url = "http://localhost:8089/test/getTeacherByStudnetId?studentId=1";
Map paramMap = new HashMap<>();
paramMap.put("studentId", 5L);
//返回形体、http头信息、http状态
ResponseEntity forEntity = restTemplate.getForEntity(url, Teacher.class, paramMap);
HttpStatus statusCode = forEntity.getStatusCode();
int statusCodeValue = forEntity.getStatusCodeValue();
Teacher teacher = forEntity.getBody();
HttpHeaders headers = forEntity.getHeaders();
System.out.println(JSON.toJSONString(statusCode));
System.out.println(JSON.toJSONString(statusCodeValue));
System.out.println(JSON.toJSONString(teacher));
System.out.println(JSON.toJSONString(headers));
// "OK"
//200
//{"name":"xxx老师","phone":"13113113152"}
//{"Content-Type":["application/json"],"Transfer-Encoding":["chunked"],"Date":["Wed, 18 May 2022 01:39:01 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]}
}
五、RestTemplate之post请求
@Autowired
RestTemplate restTemplate;
@Test
void testPosttForObject1_1() {
String url = "http://localhost:8089/test/saveStudent";
Student stu = new Student();
stu.setName("zhangsan");
stu.setAge(50);
//只能返回响应体
Student student = restTemplate.postForObject(url, stu, Student.class);
System.out.println(JSON.toJSONString(student));
// {}
}
@Test
void testPosttForObject1_2() {
String url = "http://localhost:8089/test/saveStudent";
MultiValueMap paramMap = new LinkedMultiValueMap<>();
paramMap.add("name", "zhangsan2");
paramMap.add("age", 15);
//只能返回响应体
Student student = restTemplate.postForObject(url, paramMap, Student.class);
System.out.println(JSON.toJSONString(student));
// {"age":15,"name":"zhangsan2"}
}
@Test
void testPostForEntity1() {
String url = "http://localhost:8089/test/saveStudent";
MultiValueMap paramMap = new LinkedMultiValueMap<>();
paramMap.add("name", "zhangsan2");
paramMap.add("age", 15);
//返回形体、http头信息、http状态
ResponseEntity studentResponseEntity = restTemplate.postForEntity(url, paramMap, Student.class);
System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCode()));
System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCodeValue()));
System.out.println(JSON.toJSONString(studentResponseEntity.getHeaders()));
System.out.println(JSON.toJSONString(studentResponseEntity.getBody()));
// "OK"
//200
//{"Content-Type":["application/json"],"Transfer-Encoding":["chunked"],"Date":["Wed, 18 May 2022 01:37:01 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]}
//{"age":15,"name":"zhangsan2"}
}
@Test
void testPosttForObject2_1() {
String url = "http://localhost:8089/test/saveStudent2";
Student stu = new Student();
stu.setName("zhangsan");
stu.setAge(50);
//只能返回响应体
Student student = restTemplate.postForObject(url, stu, Student.class);
System.out.println(JSON.toJSONString(student));
}
@Test
void testPosttForObject2_2() {
String url = "http://localhost:8089/test/saveStudent2";
HttpHeaders headers = new HttpHeaders();
//设置请求头为json
headers.setContentType(MediaType.APPLICATION_JSON);
Student stu = new Student();
stu.setName("zhangsan");
stu.setAge(50);
HttpEntity request = new HttpEntity<>(stu, headers);
//只能返回响应体
Student student = restTemplate.postForObject(url, request, Student.class);
System.out.println(JSON.toJSONString(student));
// {"age":50,"name":"zhangsan"}
}
@Test
void testPostForEntity2() {
String url = "http://localhost:8089/test/saveStudent2";
HttpHeaders headers = new HttpHeaders();
//设置请求头为json
headers.setContentType(MediaType.APPLICATION_JSON);
Student stu = new Student();
stu.setName("zhangsan");
stu.setAge(50);
HttpEntity request = new HttpEntity<>(stu, headers);
//返回形体、http头信息、http状态
ResponseEntity studentResponseEntity = restTemplate.postForEntity(url, request, Student.class);
System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCode()));
System.out.println(JSON.toJSONString(studentResponseEntity.getStatusCodeValue()));
System.out.println(JSON.toJSONString(studentResponseEntity.getHeaders()));
System.out.println(JSON.toJSONString(studentResponseEntity.getBody()));
//"OK"
//200
//{"Content-Type":["application/json"],"Transfer-Encoding":["chunked"],"Date":["Wed, 18 May 2022 01:38:00 GMT"],"Keep-Alive":["timeout=60"],"Connection":["keep-alive"]}
//{"age":50,"name":"zhangsan"}
}
六、RestTemplatelUtil工具类
可以返回泛型参数
@Component
public class RestTemplatelUtil {
@Autowired
RestTemplate restTemplate;
public T exchange(String url, HttpMethod method, ParameterizedTypeReference responseBodyType, A requestBody) {
RestTemplate restTemplate = new RestTemplate();
// 请求头
HttpHeaders headers = new HttpHeaders();
MimeType mimeType = MimeTypeUtils.parseMimeType("application/json");
MediaType mediaType = new MediaType(mimeType.getType(), mimeType.getSubtype(), Charset.forName("UTF-8"));
// 请求体
headers.setContentType(mediaType);
// 发送请求
HttpEntity entity = new HttpEntity<>(requestBody, headers);
ResponseEntity resultEntity = restTemplate.exchange(url, method, entity, responseBodyType);
return resultEntity.getBody();
}
}
使用方法
public ResponseToken getToken() {
//构造请求参数数据
RequestData requestData = new RequestData();
RequestLogin login = new RequestLogin();
requestData.setData(login);
//URL
String url = RequestConstantsUrl.thloginUrl;
//发起请求
ResponseData exchange = restTemplatelUtil.exchange(url, HttpMethod.POST, new ParameterizedTypeReference>() {
}, requestData);
//获取数据
return exchange.getReturnData();
}
总结:
1、xxForObject和xxForEntity区别:xxForObject返回返回体,xxForEntity返回http头部信息、http状态码、返回体。一般使用xxForEntity,判断getStatusCodeValue()为200时候,再getBody;
2、post请求和get请求,第一个参数都是URL,第二个参数post是请求的参数,get是返回接受的类;第三个参数post是返回接受的类,get是请求的参数。
restTemplate.postForEntity(url, request, Student.class); restTemplate.getForEntity(url, Teacher.class, paramMap);



