主要介绍RestTemplate的原理以及使用等
常见的http客户端请求工具:
RestTemplate是一个同步的web http客户端请求模板工具
是基于spring框架的底层的一个知识点
具体常用的方法如官网所示
RestTemplate官方文档
部分常用方法截图如下:
具体的构造方法如下:
RestTemplate默认是使用HttpURLConnection,可以通过构造方法替换底层的执行引擎,常见的引擎又HttpClient、Netty、OkHttp
如果要想替换直接如构造方法所示即可
//底层执行引擎
RestTemplate template=new RestTemplate();
//底层执行引擎ClientHttp
RestTemplate template=new RestTemplate(ClientHttpRequestFactory requestFactory);
消息
▪ 100 Continue 通知继续
▪ 101 Switching Protocols
▪ 102 Processing
成功
▪ 200 OK
▪ 201 Created
▪ 202 Accepted
▪ 203 Non-Authoritative Information
▪ 204 No Content
▪ 205 Reset Content
▪ 206 Partial Content
▪ 207 Multi-Status
重定向
▪ 300 Multiple Choices
▪ 301 Moved Permanently 永久迁移
▪ 302 Move Temporarily 临时迁移
▪ 303 See Other
▪ 304 Not Modified
▪ 305 Use Proxy
▪ 306 Switch Proxy
▪ 307 Temporary Redirect
请求错误 (客户端异常)
▪ 400 Bad Request
▪ 401 Unauthorized
▪ 402 Payment Required
▪ 403 Forbidden
▪ 404 Not Found
▪ 405 Method Not Allowed
▪ 406 Not Acceptable
▪ 407 Proxy Authentication Required
▪ 408 Request Timeout
▪ 409 Conflict
▪ 410 Gone
▪ 411 Length Required
▪ 412 Precondition Failed
▪ 413 Request Entity Too Large
▪ 414 Request-URI Too Long
▪ 415 Unsupported Media Type
▪ 416 Requested Range Not Satisfiable
▪ 417 Expectation Failed
▪ 418 I’m a teapot
▪ 421Misdirected Request
▪ 422 Unprocessable Entity
▪ 423 Locked
▪ 424 Failed Dependency
▪ 425 Too Early
▪ 426 Upgrade Required
▪ 449 Retry With
▪ 451 Unavailable For Legal Reasons
服务器错误
▪ 500 Internal Server Error
▪ 501 Not Implemented
▪ 502 Bad Gateway
▪ 503 Service Unavailable
▪ 504 Gateway Timeout
▪ 505 HTTP Version Not Supported
▪ 506 Variant Also Negotiates
▪ 507 Insufficient Storage
▪ 509 Bandwidth Limit Exceeded
▪ 510 Not Extended
▪ 600 Unparseable Response Headers
其业务逻辑层面如下所示
@RestController
public class UserController {
@GetMapping("/addUser/{#userId}/{userName}")
public UserDTO addUser(@PathVariable("userId") Long userId,
@PathVariable("userName") Long userName){
UserDTO userDTO =new UserDTO();
userDTO.setUserId(userId);
userDTO.setUserName(userName);
return UserDTO;
}
}
getForObject()
:返回对象为响应体中数据转化成的对象,基本上可以理解为Jsonpublic class RestController {
@Resource
RestTemplate restTemplate;
private static final String url = "http://localhost:8080/addUser/8888/码农研究僧";
@GetMapping("/getForObject")
public Object getForObject(){
Map<String ,Long >paramMap =new HashMap<>();
UserDTO result ==restTemplate.getForObject(url,UserDTO.class,paramMap);
//Map result =restTemplate.getForObject(url,Map.class,paramMap);
return result;
}
}
之后访问页面http://localhost:8080/getForObject即可显示其信息
getForEntity()
:返回对象为ResponseEntity对象,包含了响应中的一些重要信息,比如响应头、响应状态码、响应体等具体代码模块如下
@GetMapping("/getForEntity")
public Object getForEntity(){
Map<String ,Long >paramMap =new HashMap<>();
//ResponseEntity包装返回结果
ResponseEntity <HashMap> responseEntity =restTemplate.getForEntity(url,HashMap.class,paramMap);
//返回状态码包装类
HttpStatus statusCode =responseEntity.getStatusCode();
//返回状态码
int StatusCodeValue=responseEntity.getStatusCodeValue();
//http返回头
HttpHeaders headers=responseEntity.getHeaders();
//返回对应请求结果
return responseEntity.getBody();
post与get的区别在于post的方法传参map必须是MultiValueMap
基本类型传参和实体类型传参
//http://localhost:8080/postFor0bject1
@GetMapping("/postForObject1")
public UserDT0 postForObject1 ( ) {
//远程访问的Url UserDTO
String url = "http://localhost:8080/addUser1";
// Post方法必须使用MultiValueMap传参。//使用UserDTO传参也可以
MultiValueMap<String,0bject> paramMap = new LinkedMultiValueMap<>();
paramMap.add ("userId", 1008L);
paramMap.add ("userName ","巧克力");
UserDT0 userDTO = restTemplate.postForObject(url,paramMap,UserDT0.class);
return userDTO;
}
如果使用到@RequestMapping
,用httpentity
@RequestMapping( value = "/addUser3" )
public UserDT0 addUser3(@RequestBody UserDT0 userDTO) {
userDTo.setUserName(userDTo.getUserName() + " from RequestBody" );
return userDTO;
}
//http://localhost:8888/postForObject2
@GetMapping("/postForObject2")
public UserDT0 postForObject2( ) {
//申明一个请求头
HttpHeaders headers = new HttpHeaders();
//application/json
headers.setContentType( MediaType .APPLICATION_JSON);//远程访问的Url UserDTO
string url = "http://localhost:8080/addUser3";
/**
此处使用MultiValueMap会报错
MultiValueMap paramMap = new LinkedMultiValueMap<>( );
paramMap.add("userId",100OL) ;
paramMap.add("userName","fencaibc");*/
//此处可以使用HashMap代替,但是会有警告
UserDT0 userDTO = new UserDTO( );
userDTO.setUserId( 1088L);
userDT0.setUserName("课程");
HttpEntity<UserDTO> entityParam new HttpEntity<UserDTO>(userDTO,headers) ;
UserDT0 result = restTemplate.postFor0bject(url, entityParam,UserDTO.class);
return result ;
}
其他类似
//http://localhost:8088/ postForEntity1@GetMapping( " / postForEntity1")
public UserDT0 postForEntity1( ) {
string url = "http://localhost:8080/addUser1" ;
MultiValueMap<String,object> paramMap = new LinkedMultiValueMap<>( );
paramMap.add("userId", 100);
paramMap.add("userName" ,"课程");
ResponseEntity<UserDT0> userDTOResponseEntity =restTemplate.postForEntity(url,paramMap,UserDTO.class) ;
HttpStatus statusCode = userDTOResponseEntity.getStatusCode( );
int statusCodeValue = userDTOResponseEntity.getStatusCodeValue( );
HttpHeaders headers = userDTOResponseEntity. getHeaders( );
return userDTOResponseEntity. getBody( );
}
可以用get也可以用post
// http://localhost:8088/exchange@GetMapping("/ exchange" )
public UserDT0 exchange( ) {
//访问的远程地址UserDTO
String url= "http:// localhost:8080 addUser1" ;
//传参使用MultiValueMap
MultiValueMap<String,0bject> paramMap = new LinkedMultiValueMap<>();
paramMap.add("userId",100);
paramMap.add("userName ","exchange" );
//HttpEntity包装了传参
HttpEntity<MultiValueMap> requestEntity = new HttpEntity<>(paramMap ) ;
ResponseEntity<UserDTO> response =
restTemplate.exchange(url,HttpMethod.POST,requestEntity,UserDT0.class) ;
return response.getBody ( );
}