2.2 getForEntity()方法
| 123 | 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
| 123456789 | 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
| 12345678 | public enum HttpStatus {``public boolean is1xxInformational() {}``public boolean is2xxSuccessful() {}``public boolean is3xxRedirection() {}``public boolean is4xxClientError() {}``public boolean is5xxServerError() {}``public boolean isError() {}``} |
|---|
BodyBuilder.java
| 12345678 | 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原生的东西。
示例:
| 12345678910111213141516171819202122232425 | @Test``public 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()``true``entity.getBody()Notice{status=``200``, msg=``null``, data=[DataBean{noticeId=``21``, noticeTitle=``'aaa'``, ...``body1.toString()<``200 OK,``class com.waylau.spring.cloud.weather.pojo.Notice,{Content-Length=[``100``]}> |
|---|
当然,还有getHeaders()等方法没有举例。