RestTemplate的超全讲解(全)

前言

主要介绍RestTemplate的原理以及使用等

1. 简介

常见的http客户端请求工具:

  • jdk HttpURLConnection
  • Apache HttpClient 比较常用
  • OkHttp 比较常用

RestTemplate是一个同步的web http客户端请求模板工具
是基于spring框架的底层的一个知识点

具体常用的方法如官网所示
RestTemplate官方文档

部分常用方法截图如下:
在这里插入图片描述
具体的构造方法如下:
在这里插入图片描述
RestTemplate默认是使用HttpURLConnection,可以通过构造方法替换底层的执行引擎,常见的引擎又HttpClient、Netty、OkHttp
如果要想替换直接如构造方法所示即可

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

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

2. http状态码

  1. 消息
    100 Continue 通知继续
    ▪ 101 Switching Protocols
    ▪ 102 Processing

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

  3. 重定向
    ▪ 300 Multiple Choices
    301 Moved Permanently 永久迁移
    302 Move Temporarily 临时迁移
    ▪ 303 See Other
    ▪ 304 Not Modified
    ▪ 305 Use Proxy
    ▪ 306 Switch Proxy
    ▪ 307 Temporary Redirect

  4. 请求错误 (客户端异常)
    ▪ 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请求

其业务逻辑层面如下所示

@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():返回对象为响应体中数据转化成的对象,基本上可以理解为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;
    }
}

之后访问页面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();

4. post请求

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<String0bject> 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<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 ;
}

其他类似

//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

可以用get也可以用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 ( );
}

  • 10
    点赞
  • 70
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论
RestTemplateSpring框架提供的用于访问Restful服务的客户端工具。它提供了一组用于发送HTTP请求和处理响应的方法,可以方便地与其他的RESTful服务进行交互。 以下是一些使用RestTemplate的常见案例: 1. 发送GET请求获取资源: 使用RestTemplate发送GET请求可以获取远程服务器上的资源。可以指定请求URL、请求头信息和参数,然后使用RestTemplate的`getForObject()`或`getForEntity()`方法发送请求,并将响应结果转换为期望的Java对象。 2. 发送POST请求创建资源: 通过RestTemplate发送POST请求可以创建资源。可以指定请求URL、请求头信息和要发送的数据,然后使用RestTemplate的`postForObject()`或`postForEntity()`方法发送请求并获取响应结果。 3. 发送PUT请求更新资源: 通过RestTemplate发送PUT请求可以更新远程服务器上的资源。可以指定请求URL、请求头信息和要发送的数据,然后使用RestTemplate的`put()`方法发送请求。 4. 发送DELETE请求删除资源: 通过RestTemplate发送DELETE请求可以删除远程服务器上的资源。可以指定请求URL、请求头信息和要发送的数据,然后使用RestTemplate的`delete()`方法发送请求。 5. 上传文件: 使用RestTemplate发送POST请求上传文件。可以指定请求URL、请求头信息和要上传的文件,然后使用RestTemplate的`postForLocation()`方法发送请求。 6. 错误处理: RestTemplate可以处理HTTP请求过程中的异常。可以通过捕获`HttpStatusCodeException`来处理请求失败的情况,并获取其中的错误信息。 7. 以异步方式发送请求: RestTemplate还提供了一些以异步方式发送请求的方法,可以使用`AsyncRestTemplate`来实现。 综上所述,RestTemplate是一个非常实用的工具,可以方便地与RESTful服务进行交互,发送各种类型的HTTP请求,并处理响应结果。无论是发送GET请求获取资源,还是发送POST请求创建资源,甚至上传文件等操作,都可以通过RestTemplate来完成。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农研究僧

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值