RestTemplate详解 Springboot — 用更优雅的方式发HTTP请求( 二 )

ah.......'示例:2.1.3 带参数的get请求1Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/{1}/{2}", Notice.class,1,5);明眼人一眼能看出是用了占位符{1} 。
示例:2.1.4 带参数的get请求2Map<String,String> map = new HashMap();map.put("start","1");map.put("page","5");Notice notice = restTemplate.getForObject("http://fantj.top/notice/list/", Notice.class,map);明眼人一看就是利用map装载参数,不过它默认解析的是PathVariable的url形式 。
2.2 getForEntity()方法public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Object... uriVariables){}public <T> ResponseEntity<T> getForEntity(String url, Class<T> responseType, Map<String, ?> uriVariables){}public <T> ResponseEntity<T> getForEntity(URI url, Class<T> responseType){}与getForObject()方法不同的是返回的是ResponseEntity对象,如果需要转换成pojo,还需要json工具类的引入,这个按个人喜好用 。不会解析json的可以百度FastJson或者Jackson等工具类 。然后我们就研究一下ResponseEntity下面有啥方法 。
ResponseEntity、HttpStatus、BodyBuilder结构ResponseEntity.java
public HttpStatus getStatusCode(){}public int getStatusCodeValue(){}public boolean equals(@Nullable Object other) {}public String toString() {}public static BodyBuilder status(HttpStatus status) {}public static BodyBuilder ok() {}public static <T> ResponseEntity<T> ok(T body) {}public static BodyBuilder created(URI location) {}...HttpStatus.java
public enum HttpStatus {public boolean is1xxInformational() {}public boolean is2xxSuccessful() {}public boolean is3xxRedirection() {}public boolean is4xxClientError() {}public boolean is5xxServerError() {}public boolean isError() {}}BodyBuilder.java
public interface BodyBuilder extends HeadersBuilder<BodyBuilder> {//设置正文的长度,以字节为单位,由Content-Length标头BodyBuilder contentLength(long contentLength);//设置body的MediaType 类型BodyBuilder contentType(MediaType contentType);//设置响应实体的主体并返回它 。<T> ResponseEntity<T> body(@Nullable T body);}可以看出来,ResponseEntity包含了HttpStatus和BodyBuilder的这些信息,这更方便我们处理response原生的东西 。
示例:@Testpublic void rtGetEntity(){RestTemplate restTemplate = new RestTemplate();ResponseEntity<Notice> entity = restTemplate.getForEntity("http://fantj.top/notice/list/1/5", Notice.class);HttpStatus statusCode = entity.getStatusCode();System.out.println("statusCode.is2xxSuccessful()"+statusCode.is2xxSuccessful());Notice body = entity.getBody();System.out.println("entity.getBody()"+body);ResponseEntity.BodyBuilder status = ResponseEntity.status(statusCode);status.contentLength(100);status.body("我在这里添加一句话");ResponseEntity<Class<Notice>> body1 = status.body(Notice.class);Class<Notice> body2 = body1.getBody();System.out.println("body1.toString()"+body1.toString());}statusCode.is2xxSuccessful()trueentity.getBody()Notice{status=200, msg=null, data=https://www.isolves.com/it/cxkf/jiagou/2023-09-14/[DataBean{noticeId=21, noticeTitle='aaa', ...body1.toString()<200 OK,class com.waylau.spring.cloud.weather.pojo.Notice,{Content-Length=[100]}>当然,还有getHeaders()等方法没有举例 。
3. post请求实践

同样的,post请求也有postForObject和postForEntity 。
public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)throws RestClientException {}public <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Map<String, ?> uriVariables)throws RestClientException {}public <T> T postForObject(URI url, @Nullable Object request, Class<T> responseType) throws RestClientException {}示例
我用一个验证邮箱的接口来测试 。
@Testpublic void rtPostObject(){RestTemplate restTemplate = new RestTemplate();String url = "http://47.xxx.xxx.96/register/checkEmail";HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.AppLICATION_FORM_URLENCODED);MultiValueMap<String, String> map= new LinkedMultiValueMap<>();map.add("email", "844072586@qq.com");HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );System.out.println(response.getBody());}执行结果:
{"status":500,"msg":"该邮箱已被注册","data":null}


推荐阅读