RestTemplate 是从 Spring3.0 开始支持的一个 HTTP 请求工具
还有比较常用的httpClient,但是编码复杂,所以学习下即可,建议掌握restTemplate
一:编写配置 RestTemplateConfig
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
二:学习示例
启动postman 请求 /test/1 传入不同参数,以查看不同方式效果
import cn.study.algorithm.enty.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("test")
public class RestTemplateController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("1")
public String test(@RequestParam("id")String id){
User user=new User();
user.setUserName("test1");
user.setPassword("123");
user.setAge(22);
if(id.equals("2")){
String url="http://localhost:8080/test/2";
Map<String,String> map=new HashMap<>();
map.put("userName","zhangsan");
map.put("password","123");
map.put("age","23");
ResponseEntity<User> userResponseEntity = restTemplate.postForEntity(url, user, User.class);
return "1 restTemolate->result:"+userResponseEntity;
}else if(id.equals("3")){
String url="http://localhost:8080/test/3?username={1}&age={2}";
ResponseEntity<User> haha = restTemplate.getForEntity(url, User.class, "haha", 3);
return "1 restTemolate->result:"+haha;
}else if(id.equals("4")){
String url="http://localhost:8080/test/2";
HttpEntity<User> httpEntity=new HttpEntity<>(user);
ResponseEntity<User> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, User.class);
return "exchange->"+exchange;
}else{
RestTemplate restTemplate=new RestTemplate();
ResponseEntity<String> forEntity = restTemplate.getForEntity("https://www.baidu.com/", String.class);
System.out.println(forEntity);
return forEntity.toString();
}
}
@PostMapping("2")
public User test2(@RequestBody User user){
System.out.println("我是接口2 收到信息为-》"+user);
user.setUserName("test2");
return user;
}
@GetMapping("3")
public User test3(@RequestParam("username")String username,@RequestParam("age")Integer age){
System.out.println("我是接口3 收到信息为-》"+username);
User user=new User();
user.setUserName(username);
user.setAge(age);
return user;
}
}
User.enty
@Data
public class User {
private String userName;
private String password;
private Integer age;
}
|