当前位置: 首页 > news >正文

宣讲家网站生态文明建设电商代运营公司100强

宣讲家网站生态文明建设,电商代运营公司100强,湖北短视频seo推荐,深圳网站建设公司小江目录 1.什么是RestTemplate? 2.RestTemplate的使用 2.1spring环境下 注意1#xff1a;RestTemplate中发送请求execute()和exchange()方法的区别 execute()方式 exchange()方式 二者的区别 注意2#xff1a;进阶配置——底层HTTP客户端 2.2非spring环境下 1.什么是R…目录 1.什么是RestTemplate? 2.RestTemplate的使用 2.1spring环境下 注意1RestTemplate中发送请求execute()和exchange()方法的区别 execute()方式 exchange()方式 二者的区别 注意2进阶配置——底层HTTP客户端 2.2非spring环境下 1.什么是RestTemplate? RestTemplate是一款Spring框架中的HTTP客户端工具类库它封装了大量的HTTP请求处理代码使得我们可以方便地进行HTTP请求的发送与处理。RestTemplate支持多种HTTP请求方式例如GET、POST、PUT、DELETE等同时也支持参数的传递与响应结果的解析等功能使得我们在进行RESTful风格的API开发时更加方便。 2.RestTemplate的使用 RestTemplate的使用分为俩种方式一种是spring环境一种是非spring环境 2.1spring环境下 添加pom依赖 dependencygroupIdorg.springframework.boot/groupIdartifactIdspring-boot-starter-web/artifactId /dependency 添加RestTemplate配置类 import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate;Configuration public class RestTemplateConfig {/*** 没有实例化RestTemplate时初始化RestTemplate* return*/ConditionalOnMissingBean(RestTemplate.class)Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate new RestTemplate();return restTemplate;} } 使用示例 import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.client.RequestCallback; import org.springframework.web.client.ResponseExtractor; import org.springframework.web.client.RestTemplate;import java.util.Map;/*** RestTemplate Use Example Demo** author JiuLi*/ Controller public class RestTemplateCtrl {Autowiredprivate RestTemplate restTemplate;/*** exchange()形式** param data* return*/RequestMapping(value /resttemplate/getNative, method RequestMethod.GET)public String restTemplateNativeTest(Map data) {// 请求头HttpHeaders httpHeaders new HttpHeaders();HttpEntityObject httpEntity new HttpEntity(data, httpHeaders);String url ;// 发送请求ResponseEntity entity restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);// 获取请求回调JSONObject jsonObject JSONObject.parseObject(JSON.toJSON(entity.getBody()).toString());// 打印请求返回信息return jsonObject.toJSONString();}/*** execute()形式** param data* return*/RequestMapping(value /resttemplate/getreqAndrep, method RequestMethod.GET)public String restTemplateTest(Map data) {// 请求头HttpHeaders httpHeaders new HttpHeaders();HttpEntityObject httpEntity new HttpEntity(httpHeaders);// 请求提取器RequestCallback requestCallback restTemplate.httpEntityCallback(httpEntity, Map.class);// 响应提取器ResponseExtractorResponseEntityMap responseExtractor restTemplate.responseEntityExtractor(Map.class);String url ;// 发送请求ResponseEntity entity restTemplate.execute(url, HttpMethod.GET, requestCallback, responseExtractor, data);// 获取请求回调JSONObject jsonObject JSONObject.parseObject(JSON.toJSON(entity.getBody()).toString());// 打印请求返回信息return jsonObject.toJSONString();}} 注意1RestTemplate中发送请求execute()和exchange()方法的区别 在使用RestTemplate发送HTTP请求时我们通常会使用execute()或exchange()方法来发送请求。这两个方法的作用类似但是有一些区别在本篇博客中我们将介绍execute()和exchange()方法的区别。 execute()方式 execute()方法是RestTemplate中最基本的请求方法它的定义如下 public T T execute(String url, HttpMethod method, RequestCallback requestCallback,ResponseExtractorT responseExtractor) throws RestClientException {// ... }传入四个参数请求URL、HTTP请求方法、RequestCallback对象和ResponseExtractor对象。其中RequestCallback代表着请求体可以通过实现该接口来设置请求体的内容ResponseExtractor代表着响应结果的处理器可以通过实现该接口来对响应结果进行解析。 execute()方法可以返回任意类型的响应结果包括自定义类型、String类型等由ResponseExtractor对象决定。 exchange()方式 exchange()方法的定义如下 public T ResponseEntityT exchange(String url, HttpMethod method, HttpEntity? requestEntity,ClassT responseType, Object... uriVariables) throws RestClientException {// ... }与execute()方法不同exchange()方法返回的是ResponseEntityT类型的响应结果对象。ResponseEntity包含了响应状态码响应头以及响应体等信息。 exchange()方法的请求体为HttpEntity对象而非RequestCallback对象。HttpEntity用于封装请求体和请求头信息。 除此之外在exchange()方法中还可以传入uriVariables参数。这个参数用于替换URL中的变量例如 String url http://localhost:8080/{id}; ResponseEntityUser response restTemplate.exchange(url, HttpMethod.GET, null, User.class, 1);在上述代码中我们通过exchange()方法使用占位符{id}替换URL中的变量并将变量的值设置为1。 二者的区别 execute()方法更加灵活可以处理任意类型的响应结果同时请求体也更加自由。而exchange()方法则更加直观能够提供完整的响应对象方便进行状态码和响应头的解析。 当我们只需要简单地获取响应结果时可以使用execute()方法而在需要对响应状态码、响应头等信息进行处理时建议使用exchange()方法。 注意2进阶配置——底层HTTP客户端 如上方式添加的RestTemplate配置类默认使用的是JDK自带的HttpURLConnection客户端作为底层的HTTP客户端实现的实际上使用默认的HttpURLConnection客户端已经足够我们进行一系列的Http请求操作了但是具体受限于某些需求或项目要求HttpURLConnection客户端不满足一些我们的需求那么我们可以通过配置替换的方式指定使用HttpClient客户端替换默认的客户端HttpClient是一个功能强大、高度可定制、性能优越的HTTP客户端工具类库它可以满足更多复杂的HTTP请求需求。 使用HttpClient客户端好处 1.支持连接池使用HttpClient作为底层客户端可以支持连接池机制减少每次请求建立连接和关闭连接的开销提高请求效率。而默认的HttpURLConnection会在每次请求时重新建立连接效率较低。 2.支持自定义拦截器使用HttpClient可以通过自定义拦截器来实现一些特殊的功能例如HTTP认证、请求重试等。而HttpURLConnection则很难通过自定义拦截器来实现这些功能。 3.支持更多协议HttpClient支持HTTP协议以外的协议例如HTTPS、FTP等。 缺点 1.需要额外配置如果使用HttpClient作为底层客户端需要引入相应的依赖并进行相应的配置增加了使用成本。 2.可能会有线程安全的问题默认情况下HttpClient是不线程安全的如果在多线程环境下并发使用同一个HttpClient实例可能会出现线程安全问题。为了避免这个问题我们可以采用各种线程安全的HttpClient实现方式例如使用PoolingHttpClientConnectionManager来管理连接池。 使用Httpclient在RestTemplateConfig配置即可 首先需要添加pom依赖 dependencygroupIdorg.apache.httpcomponents/groupIdartifactIdhttpclient/artifactIdversion${httpclient.version}/version /dependency 方式一 import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate;Configuration public class RestTemplateConfig {/*** 没有实例化RestTemplate时初始化RestTemplate* return*/ConditionalOnMissingBean(RestTemplate.class)Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate new RestTemplate();return restTemplate;}/*** 使用HttpClient作为底层客户端* return*/private ClientHttpRequestFactory getClientHttpRequestFactory() {int timeout 5000;RequestConfig config RequestConfig.custom().setConnectTimeout(timeout).setConnectionRequestTimeout(timeout).setSocketTimeout(timeout).build();CloseableHttpClient client HttpClientBuilder.create().setDefaultRequestConfig(config).build();return new HttpComponentsClientHttpRequestFactory(client);}} 方式二 import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate;Configuration public class RestTemplateConfig {/*** 没有实例化RestTemplate时初始化RestTemplate* return*/ConditionalOnMissingBean(RestTemplate.class)Beanpublic RestTemplate restTemplate(){CloseableHttpClient httpClient HttpClients.custom().setConnectionManager(new PoolingHttpClientConnectionManager()).build();HttpComponentsClientHttpRequestFactory requestFactory new HttpComponentsClientHttpRequestFactory();requestFactory.setHttpClient(httpClient);RestTemplate restTemplate new RestTemplate();return restTemplate;}} 当然还有其他的Http客户端例如OKHttpClientOKHttpClient优于Httpclient优于默认的HttpURLConnection具体如何选择看开发需求以下是使用OKHttpClient的配置 import okhttp3.OkHttpClient; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.client.ClientHttpRequestFactory; import org.springframework.http.client.OkHttp3ClientHttpRequestFactory; import org.springframework.web.client.RestTemplate;import java.util.concurrent.TimeUnit;Configuration public class RestTemplateConfig {/*** 没有实例化RestTemplate时初始化RestTemplate* return*/ConditionalOnMissingBean(RestTemplate.class)Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate new RestTemplate();return restTemplate;}/*** 使用OkHttpClient作为底层客户端* return*/private ClientHttpRequestFactory getClientHttpRequestFactory(){OkHttpClient okHttpClient new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS).writeTimeout(5, TimeUnit.SECONDS).readTimeout(5, TimeUnit.SECONDS).build();return new OkHttp3ClientHttpRequestFactory(okHttpClient);}} 2.2非spring环境下 导入依赖 如果当前项目不是Spring项目加入spring-web包即可引入RestTemplate类 dependencygroupIdorg.springframework/groupIdartifactIdspring-web/artifactIdversion5.2.6.RELEASE/version /dependency 使用new的形式获取到RestTemplate的实例以发送get请求为例进行测试 public void simpleTest() {RestTemplate restTemplate new RestTemplate();String url ;String str restTemplate.getForObject(url, String.class);System.out.println(str); } 所以当在非spring环境下需要使用resttemplate时只需要使用New获取到restTmeplate的实例然后再进行之后所需要的收发Http请求的操作即可
http://www.eeditor.cn/news/119550/

相关文章:

  • 网站建设选谋者智能小程序开发
  • 华为网站开发app下载平台哪个好
  • 当当网网站建设案例网络营销外包价格
  • 古典风格网站模板htmlwordpress主题的连接函数
  • 中国十大企业襄阳网站seo方法
  • 企业网站的重要性钉钉付费版多少钱
  • 深圳网站建设公司建设wordpress插件 标签
  • 华梦服饰网站建设中北京市建设厅网站首页
  • 天津正规网站建设调试公司网站设计目的与规划
  • 在家里怎样做网站如何写网站建设实验结果分析
  • 建网站原型图中小企业门户网站建设策略
  • 优惠券直播网站怎么做的郑州汉狮做网站多少钱
  • 静态网站建设的流程人才网站app建设建议
  • 电子商务和网站建设区别软件发展的四个阶段
  • 黄山工程建设信息网站电子商务网站dw建设实验报告
  • 房产网站建设产品中国十大建筑设计院
  • 资质类网站如何做优化专业的教育行业网站制作
  • 做游戏网站的目地有没有在家做的手工活网站
  • 做康复医院网站怎样找到工厂直招网站
  • 网站建设:成都今网科技wordpress 大气模板
  • 网站地图用法大安网站建设
  • 宁夏建设工程交易中心网站记事本做网站怎么插图
  • 鸣蝉网站建设公司建筑公司网站管理员
  • 域名如何做网站百度云 免费 网站主机
  • 烟台优化网站公司wordpress 主题 教程
  • 网站建站步骤做外贸需掌握的网站
  • 展开网站建设网站模板 psd
  • 台州建设网站公司生鲜电商网站建设
  • 中国十大门户网站排行金蝶软件有限公司
  • 云浮新兴哪有做网站的在山东和网页有关的公司