springboot RestTemplate

·  阅读 2136

1.springboot不会自动注册RestTemplate,需要自己注册bean

	@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
return builder.build();
}
复制代码

2.创建测试的controller,创建一个get请求和一个post请求作为演示

@Data
public class User {
private Long id;
private String name;
private Integer age;
}

@RestController
public class TestController {

@GetMapping("getString")
public String getString(String src){
return src;
}

@PostMapping("getUser")
public User getUser(@RequestBody User user){
return user;
}
}
复制代码

3.测试

  • 测试get请求
@RunWith(SpringRunner.class)
@SpringBootTest
public class ResttemplateApplicationTests {
@Autowired
private RestTemplate restTemplate;

@Test
public void testGetRequest(){
//2种方式获取
//1.直接获取响内容
String object = restTemplate.getForObject("http://localhost:8080/getString?src=hello", String.class);
System.out.println(object);

//2.获取响应信息,包含响应状态、响应头、响应内容
ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080/getString?src=hello", String.class);
System.out.println(entity);
//响应状态码
System.out.println(entity.getStatusCode());
//响应头
System.out.println(entity.getHeaders());
//响应内容
System.out.println(entity.getBody());
}
}
复制代码
  • 测试post请求
	//post请求和get请求一样,支持2种方式
@Test
public void testPostRequest(){
//设置传递的参数
Map<String, Object> postData = new HashMap<>();
postData.put("id", 1L);
postData.put("name", "测试");
postData.put("age", 18);
User user = restTemplate.postForObject("http://localhost:8080/getUser", postData, User.class);
System.out.println(user);
}
复制代码
  • post请求设置请求头
	@Test
public void testPostHeaders(){
//设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("Content-Type", "application/json;charset=utf-8");

//设置请求参数
Map<String, Object> postData = new HashMap<>();
postData.put("id", 1L);
postData.put("name", "测试");
postData.put("age", 18);

//将请求头和请求参数设置到HttpEntity中
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(postData, httpHeaders);

User user = restTemplate.postForObject("http://localhost:8080/getUser", httpEntity, User.class);
System.out.println(user);
}
复制代码

项目路径


作者博客

作者公众号 在这里插入图片描述

分类:
后端
标签:
分类:
后端
标签: