RestTemplate's super-full explanation (full)

foreword

Mainly introduce the principle and use of RestTemplate

1 Introduction

Common http client request tools:

  • jdk HttpURLConnection
  • Apache HttpClient is more commonly used
  • OkHttp is more commonly used

RestTemplate is a synchronous web http client request template tool
based on the underlying knowledge point of the spring framework

The specific and commonly used methods are shown in the official website
of RestTemplate official document

The screenshots of some commonly used methods are as follows:
insert image description here
The specific construction method is as follows:
insert image description here
RestTemplate uses HttpURLConnection by default, and the underlying execution engine can be replaced by the construction method. The common engines are HttpClient, Netty, OkHttp.
If you want to replace it, just follow the construction method

//底层执行引擎
RestTemplate template=new RestTemplate();

//底层执行引擎ClientHttp
RestTemplate template=new RestTemplate(ClientHttpRequestFactory requestFactory);

2. http status code

  1. news
    _100 ContinueNotice continues
    ▪ 101 Switching Protocols
    ▪ 102 Processing

  2. success
    _200 OK
    ▪ 201 Created
    ▪ 202 Accepted
    ▪ 203 Non-Authoritative Information
    ▪ 204 No Content
    ▪ 205 Reset Content
    ▪ 206 Partial Content
    ▪ 207 Multi-Status

  3. Redirect
    ▪ 300 Multiple Choices
    301 Moved PermanentlyPermanent
    Migration▪302 Move TemporarilyTemporary migration
    ▪ 303 See Other
    ▪ 304 Not Modified
    ▪ 305 Use Proxy
    ▪ 306 Switch Proxy
    ▪ 307 Temporary Redirect

  4. Request error (client exception)
    ▪ 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

  5. 服务器错误
    ▪ 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

3. get request

Its business logic level is as follows

@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(): The returned object is the object converted from the data in the response body, which can basically be understood as Json
public 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<String ,Long > result =restTemplate.getForObject(url,Map.class,paramMap);
		return result;
    }
}

Then visit the page http://localhost:8080/getForObject to display its information

  • getForEntity(): The returned object is a ResponseEntity object, which contains some important information in the response, such as response header, response status code, response body, etc.

The specific code modules are as follows

 @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();

4. post request

The difference between post and get is that the post method parameter map must be a MultiValueMap

Basic type parameter passing and entity type parameter passing

//http://localhost:8080/postFor0bject1
@GetMapping("/postForObject1")
public UserDT0 postForObject1 ( ) {
    
    
	//远程访问的Url UserDTO
	String url = "http://localhost:8080/addUser1";
	// Post方法必须使用MultiValueMap传参。//使用UserDTO传参也可以
	
	MultiValueMap<String0bject> paramMap = new LinkedMultiValueMap<>();
	paramMap.add ("userId", 1008L);
	paramMap.add ("userName ""巧克力");
	UserDT0 userDTO = restTemplate.postForObject(url,paramMap,UserDT0.class);
	return userDTO;
}

If used @RequestMapping, use 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<String,0bject> 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 ;
}

other similar

//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( );
}

5. Exchange

You can use get or post

// http://localhost:8088/exchange@GetMapping("/ exchange" )
public UserDT0 exchange( ) {
    
    
	//访问的远程地址UserDTO
	String url= "http:// localhost:8080 addUser1" ;
	//传参使用MultiValueMap
	MultiValueMap<String0bject> 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 ( );
}

Guess you like

Origin blog.csdn.net/weixin_47872288/article/details/121842374#comments_26955346