九色国产,午夜在线视频,新黄色网址,九九色综合,天天做夜夜做久久做狠狠,天天躁夜夜躁狠狠躁2021a,久久不卡一区二区三区

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
RestTemplate使用教程

一、概述

spring框架提供的RestTemplate類可用于在應(yīng)用中調(diào)用rest服務(wù),它簡(jiǎn)化了與http服務(wù)的通信方式,統(tǒng)一了RESTful的標(biāo)準(zhǔn),封裝了http鏈接, 我們只需要傳入url及返回值類型即可。相較于之前常用的HttpClient,RestTemplate是一種更優(yōu)雅的調(diào)用RESTful服務(wù)的方式。

在Spring應(yīng)用程序中訪問第三方REST服務(wù)與使用Spring RestTemplate類有關(guān)。RestTemplate類的設(shè)計(jì)原則與許多其他Spring *模板類(例如JdbcTemplate、JmsTemplate)相同,為執(zhí)行復(fù)雜任務(wù)提供了一種具有默認(rèn)行為的簡(jiǎn)化方法。

RestTemplate默認(rèn)依賴JDK提供http連接的能力(HttpURLConnection),如果有需要的話也可以通過setRequestFactory方法替換為例如 Apache HttpComponents、Netty或OkHttp等其它HTTP library。

考慮到RestTemplate類是為調(diào)用REST服務(wù)而設(shè)計(jì)的,因此它的主要方法與REST的基礎(chǔ)緊密相連就不足為奇了,后者是HTTP協(xié)議的方法:HEAD、GET、POST、PUT、DELETE和OPTIONS。例如,RestTemplate類具有headForHeaders()、getForObject()、postForObject()、put()和delete()等方法。

二、實(shí)現(xiàn)

最新api地址:https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html

RestTemplate包含以下幾個(gè)部分:

  • HttpMessageConverter 對(duì)象轉(zhuǎn)換器
  • ClientHttpRequestFactory 默認(rèn)是JDK的HttpURLConnection
  • ResponseErrorHandler 異常處理
  • ClientHttpRequestInterceptor 請(qǐng)求攔截器

常規(guī)配置

 public MyRestClientService(RestTemplateBuilder restTemplateBuilder) {          this.restTemplate = restTemplateBuilder              .basicAuthorization("username", "password")              .setConnectTimeout(3000)              .setReadTimeout(5000)              .rootUri("http://api.example.com/")              .build();      }


ClientHttpRequestInterceptor

學(xué)習(xí)使用帶有Spring RestTemplate的ClientHttpRequestInterceptor,以Spring AOP風(fēng)格記錄請(qǐng)求和響應(yīng)頭和主體。

攔截器記錄請(qǐng)求和響應(yīng)
import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpRequest;import org.springframework.http.client.ClientHttpRequestExecution;import org.springframework.http.client.ClientHttpRequestInterceptor;import org.springframework.http.client.ClientHttpResponse;import org.springframework.util.StreamUtils;  import java.io.IOException;import java.nio.charset.Charset; public class RequestResponseLoggingInterceptor implements ClientHttpRequestInterceptor {          private final Logger log = LoggerFactory.getLogger(this.getClass());      @Override    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException    {        logRequest(request, body);        ClientHttpResponse response = execution.execute(request, body);        logResponse(response);         //Add optional additional headers        response.getHeaders().add("headerName", "VALUE");         return response;    }      private void logRequest(HttpRequest request, byte[] body) throws IOException    {        if (log.isDebugEnabled())        {            log.debug("===========================request begin================================================");            log.debug("URI         : {}", request.getURI());            log.debug("Method      : {}", request.getMethod());            log.debug("Headers     : {}", request.getHeaders());            log.debug("Request body: {}", new String(body, "UTF-8"));            log.debug("==========================request end================================================");        }    }      private void logResponse(ClientHttpResponse response) throws IOException    {        if (log.isDebugEnabled())        {            log.debug("============================response begin==========================================");            log.debug("Status code  : {}", response.getStatusCode());            log.debug("Status text  : {}", response.getStatusText());            log.debug("Headers      : {}", response.getHeaders());            log.debug("Response body: {}", StreamUtils.copyToString(response.getBody(), Charset.defaultCharset()));            log.debug("=======================response end=================================================");        }    }}
注冊(cè)ClientHttpRequestInterceptor
@Beanpublic RestTemplate restTemplate(){    RestTemplate restTemplate = new RestTemplate();     restTemplate.setRequestFactory(newBufferingClientHttpRequestFactory(clientHttpRequestFactory()));    restTemplate.setMessageConverters(Collections.singletonList(mappingJacksonHttpMessageConverter()));     restTemplate.setInterceptors( Collections.singletonList(newRequestResponseLoggingInterceptor()) );     return restTemplate;}

 

三、請(qǐng)求示例

GET

private static void getEmployees(){    final String uri = "http://localhost:8080/springrestexample/employees";         RestTemplate restTemplate = new RestTemplate();    String result = restTemplate.getForObject(uri, String.class);         System.out.println(result);}
使用RestTemplate定制HTTP頭文件
private static void getEmployees(){    final String uri = "http://localhost:8080/springrestexample/employees";         RestTemplate restTemplate = new RestTemplate();         HttpHeaders headers = new HttpHeaders();    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);         ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.GET, entity, String.class);         System.out.println(result);}
Get請(qǐng)求獲取響應(yīng)為一個(gè)對(duì)象
private static void getEmployees(){    final String uri = "http://localhost:8080/springrestexample/employees";    RestTemplate restTemplate = new RestTemplate();         EmployeeListVO result = restTemplate.getForObject(uri, EmployeeListVO.class);         System.out.println(result);}
URL 參數(shù)
private static void getEmployeeById(){    final String uri = "http://localhost:8080/springrestexample/employees/{id}";         Map<String, String> params = new HashMap<String, String>();    params.put("id", "1");         RestTemplate restTemplate = new RestTemplate();    EmployeeVO result = restTemplate.getForObject(uri, EmployeeVO.class, params);         System.out.println(result);}

POST

private static void createEmployee(){    final String uri = "http://localhost:8080/springrestexample/employees";     EmployeeVO newEmployee = new EmployeeVO(-1, "Adam", "Gilly", "test@email.com");     RestTemplate restTemplate = new RestTemplate();    EmployeeVO result = restTemplate.postForObject( uri, newEmployee, EmployeeVO.class);     System.out.println(result);}
Submit Form Data
HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> map= new LinkedMultiValueMap<>();map.add("id", "1"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); RestTemplate restTemplate = new RestTemplate();EmployeeVO result = restTemplate.postForObject( uri, request, EmployeeVO.class);System.out.println(result);

PUT

private static void updateEmployee(){    final String uri = "http://localhost:8080/springrestexample/employees/{id}";         Map<String, String> params = new HashMap<String, String>();    params.put("id", "2");         EmployeeVO updatedEmployee = new EmployeeVO(2, "New Name", "Gilly", "test@email.com");         RestTemplate restTemplate = new RestTemplate();    restTemplate.put ( uri, updatedEmployee, params);}
Simple PUT 
Foo updatedInstance = new Foo("newName");updatedInstance.setId(createResponse.getBody().getId());String resourceUrl =   fooResourceUrl + '/' + createResponse.getBody().getId();HttpEntity<Foo> requestUpdate = new HttpEntity<>(updatedInstance, headers);template.exchange(resourceUrl, HttpMethod.PUT, requestUpdate, Void.class);
使用.exchange和請(qǐng)求回調(diào)
RequestCallback requestCallback(final Foo updatedInstance) {    return clientHttpRequest -> {        ObjectMapper mapper = new ObjectMapper();        mapper.writeValue(clientHttpRequest.getBody(), updatedInstance);        clientHttpRequest.getHeaders().add(          HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);        clientHttpRequest.getHeaders().add(          HttpHeaders.AUTHORIZATION, "Basic " + getBase64EncodedLogPass());    };}


DELETE

private static void deleteEmployee(){    final String uri = "http://localhost:8080/springrestexample/employees/{id}";         Map<String, String> params = new HashMap<String, String>();    params.put("id", "2");         RestTemplate restTemplate = new RestTemplate();    restTemplate.delete ( uri,  params );}

參考資料:

https://howtodoinjava.com/spring-restful/spring-restful-client-resttemplate-example/

https://www.xncoding.com/2017/07/06/spring/sb-restclient.html

https://www.baeldung.com/rest-template

本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
優(yōu)雅的http請(qǐng)求方式RestTemplate,讓人愛不釋手
從零搭建 Spring Cloud 服務(wù)(超級(jí)詳細(xì))
Spring Cloud入門教程(二):客戶端負(fù)載均衡(Ribbon)
Spring RestTemplate中幾種常見的請(qǐng)求方式
Spring RestTemplate詳解
RestTemplate post請(qǐng)求
更多類似文章 >>
生活服務(wù)
熱點(diǎn)新聞
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服