SpringBoot使用RestTemplate實(shí)現(xiàn)HTTP請求詳解
1. 簡單使用
RestTemplate底層是通過HttpURLConnection實(shí)現(xiàn)的。
(1)getForObject
RestTemplate restTemplate = new RestTemplate(https://blog.csdn.net/mryang125/article/details/80955558);
String url = "http://localhost:8080/user/{id}";
UserVo userVo = restTemplate.getForObject(url, UserVo.class, id);
第一個參數(shù)表示URL,第二個參數(shù)表示返回類型,第三個參數(shù)表示URI中對應(yīng)的參數(shù),是一個可變長參數(shù),可按順序?qū)懚鄠€參數(shù)。
(2)getForEntity
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/users/{userName}/{note}/{start}/{limit}";
//使用map封裝多個參數(shù)
Map<String, Object> params = new HashMap<>();
params.put("userName", userName);
params.put("note", note);
params.put("start", start);
params.put("limit", limit);
ResponseEntity<List> responseEntity = restTemplate.getForEntity(url, List.class, params);
List<UserVo> userVos = responseEntity.getBody();
(3)postForObject
RestTemplate restTemplate = new RestTemplate(); String url = "http://localhost:8080/user"; //設(shè)置請求頭 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //創(chuàng)建請求實(shí)體對象 HttpEntity<UserVo> request = new HttpEntity<>(newUserVo, headers); User user = restTemplate.postForObject(url, request, User.class);
(4)postForEntity
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/user";
//設(shè)置請求頭
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//創(chuàng)建請求實(shí)體對象
HttpEntity<UserVo> request = new HttpEntity<>(newUserVo, headers);
//請求服務(wù)器
ResponseEntity<User> responseEntity = restTemplate.postForEntity(url, request, User.class);
//獲取響應(yīng)體
User user = responseEntity.getBody();
//獲取響應(yīng)頭
HttpHeaders respHeaders = responseEntity.getHeaders();
//獲取響應(yīng)屬性
List<String> success = respHeaders.get("success");
//獲取響應(yīng)狀態(tài)碼
int statusCode = responseEntity.getStatusCodeValue();
(5)delete
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete("http://localhost:8080/use/{id}", id);
(6)exchange
RestTemplate還提供了一個exchange方法,該方法比上面的方法靈活,可以通過制定參數(shù)實(shí)現(xiàn)各種Http請求。下面列出Spring提供的八種方法。
<T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables) throws RestClientException; <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType, Map<String, ?> uriVariables) throws RestClientException; <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, Class<T> responseType) throws RestClientException; <T> ResponseEntity<T> exchange(String url,HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Object... uriVariables) throws RestClientException; <T> ResponseEntity<T> exchange(String url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType, Map<String, ?> uriVariables) throws RestClientException; <T> ResponseEntity<T> exchange(URI url, HttpMethod method, HttpEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException; <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, Class<T> responseType) throws RestClientException; <T> ResponseEntity<T> exchange(RequestEntity<?> requestEntity, ParameterizedTypeReference<T> responseType) throws RestClientException;
下面寫一個使用例子:
RestTemplate restTemplate = new RestTemplate();
String url = "http://localhost:8080/user";
//設(shè)置請求頭
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
//創(chuàng)建請求實(shí)體對象
HttpEntity<UserVo> request = new HttpEntity<>(newUserVo, headers);
//請求服務(wù)器
ResponseEntity<User> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, User.class);
//獲取響應(yīng)體
User user = responseEntity.getBody();
//獲取響應(yīng)頭
HttpHeaders respHeaders = responseEntity.getHeaders();
//獲取響應(yīng)屬性
List<String> success = respHeaders.get("success");
//獲取響應(yīng)狀態(tài)碼
int statusCode = responseEntity.getStatusCodeValue();
//獲取資源
String url1 = "http://localhost:8080/user/{id}";
ResponseEntity<User> responseEntity1 = restTemplate.exchange(url1, HttpMethod.GET, null, User.class, id);
//獲取響應(yīng)體
User user1 = responseEntity1.getBody();
2. 使用泛型
使用泛型接收響應(yīng),這里添加一個返回類型中泛型的使用方法:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
//創(chuàng)建請求實(shí)體對象,這里將參數(shù)轉(zhuǎn)換為JSON字符串了
HttpEntity<String> request = new HttpEntity<>(paramJsonStr, headers);
//請求服務(wù)器
RestTemplate restTemplate = new RestTemplate();
String url = "http://www.baidu.com/task";
ResponseEntity<String> responseEntity = null;
try {
//統(tǒng)一使用String接收響應(yīng),再用Jackson轉(zhuǎn)為對應(yīng)的實(shí)體類
responseEntity = restTemplate.postForEntity(url, request, String.class);
//這里使用try...catch是因?yàn)橛锌赡芤驗(yàn)榫W(wǎng)絡(luò)原因出現(xiàn)錯誤,RestClientException 的子類 ResourceAccessException 異常
} catch (RestClientException e) {
e.printStackTrace();
}
if (responseEntity != null) {
//獲取響應(yīng)體
String body = responseEntity.getBody();
//使用Jackson轉(zhuǎn)為對應(yīng)的實(shí)體類,這里的Result中使用到了泛型,用來應(yīng)對多種格式
ObjectMapper mapper = new ObjectMapper();
Result<Ret> result = mapper.readValue(body, new TypeReference<Result<Ret>>() {});
if (result != null) {
//使用了泛型,不同的請求這里就可以獲取到不同類型的data
Ret data = result.getData();
System.out.println("data : " + data);
}
}
@Data
public class Result<T> {
private String logid;
private T data;
private Integer status;
private String message;
private Double st;
private Double crt;
}
@Data
public class Ret {
private Boolean ret;
private String photoId;
}
以上就是SpringBoot使用RestTemplate實(shí)現(xiàn)HTTP請求詳解的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot RestTemplate實(shí)現(xiàn)HTTP請求的資料請關(guān)注腳本之家其它相關(guān)文章!
- SpringBoot使用RestTemplate發(fā)送http請求的實(shí)操演示
- springboot中RestTemplate發(fā)送HTTP請求的實(shí)現(xiàn)示例
- springboot中RestTemplate配置HttpClient連接池詳解
- 基于springboot的RestTemplate、okhttp和HttpClient對比分析
- SpringBoot 利用RestTemplate http測試
- 關(guān)于springboot 中使用httpclient或RestTemplate做MultipartFile文件跨服務(wù)傳輸?shù)膯栴}
- SpringBoot使用RestTemplate如何通過http請求將文件下載到本地
相關(guān)文章
Nacos配置文件使用經(jīng)驗(yàn)及CAP原則詳解
這篇文章主要為大家介紹了Nacos配置文件使用經(jīng)驗(yàn)及CAP規(guī)則詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-02-02
MyBatis-Plus攔截器對敏感數(shù)據(jù)實(shí)現(xiàn)加密
做課程項(xiàng)目petstore時遇到需要加密屬性的問題,而MyBatis-Plus為開發(fā)者提供了攔截器的相關(guān)接口,本文主要介紹通過MyBatis-Plus的攔截器接口自定義一個攔截器類實(shí)現(xiàn)敏感數(shù)據(jù)如用戶密碼的加密功能,感興趣的可以了解一下2021-11-11
Java實(shí)現(xiàn)ArrayList自動擴(kuò)容
ArrayList的擴(kuò)容規(guī)則是非常簡單的,它會根據(jù)需要自動擴(kuò)容,本文就來介紹一下Java實(shí)現(xiàn)ArrayList自動擴(kuò)容,具有一定的參考價值,感興趣的可以了解一下2023-12-12
Spring的異常處理@ExceptionHandler注解解析
這篇文章主要介紹了Spring的異常處理@ExceptionHandler注解解析,當(dāng)一個Controller中有方法加了@ExceptionHandler之后,這個Controller其他方法中沒有捕獲的異常就會以參數(shù)的形式傳入加了@ExceptionHandler注解的那個方法中,需要的朋友可以參考下2023-12-12

