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

RestTemplate

RestTemplate介绍

RestTemplate是Spring提供的用于访问RESTful服务的客户端,RestTemplate提供了多种便捷访问远程Http服务的方法,能够大大提高客户端的编写效率。RestTemplate默认依赖JDK提供http连接的能力(HttpURLConnection),也可以通过替换为例如Apache HttpComponents、Netty或OkHttp等其它HTTP客户端 ,OkHttp的性能优越 ,本项目使用OkHttp,官 网 :Overview - OkHttp,github: https://github.com/square/okhttp。

RestTemplate效果测试

1.依赖

<dependency><groupId>com.squareup.okhttp3</groupId><artifactId>okhttp</artifactId>
</dependency>

2.配置 

@Bean
public RestTemplate restTemplate() {return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
}

3.测试类

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;@RunWith(SpringRunner.class)
@SpringBootTest
public class TemplateTest {@Autowiredprivate RestTemplate restTemplate;@Testpublic void test(){String url = "http://www.baidu.com";ResponseEntity<String> forEntity = restTemplate.getForEntity(url, String.class);System.out.println("网页结果:"+forEntity.getBody());}}

 

网页内容中中文乱码解决方案:

原因:

当RestTemplate默认使用String存储body内容时默认使用ISO_8859_1字符集。

解决:

配置StringHttpMessageConverter 消息转换器,使用utf-8字符集。

修改RestTemplate的定义方法

  @Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate = new RestTemplate(new OkHttp3ClientHttpRequestFactory());//获取配置转换器List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();//设置编码格式messageConverters.set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));//将转换器修改后的对象再赋值回去,对原来对象属性进行修改restTemplate.setMessageConverters(messageConverters);return restTemplate;}

OkHttp3ClientHttpRequestFactory()

Ctrl+单击点进去查看源码

继续跟进

 光标在接口上ClientHttpRequestFactory

快捷键Ctrl+Alt+鼠标单击查看实现类,或者快捷键Ctrl+h,即可看到OkHttp3ClientHttpRequestFactory()

http://www.lryc.cn/news/128610.html

相关文章:

  • rabbitMQ服务自动停止(已解决
  • Qt平滑弹出页面
  • 第07天 Static关键字作用及用法
  • Redis扩容与一致性Hash算法解析
  • 【第七讲---视觉里程计1】
  • Linux: sched: might_sleep; 一个调试函数,演变为真实的睡眠函数,实至名归
  • (三) 搞定SOME/IP通信之CommonAPI库
  • windows bat脚本,使用命令行增加/删除防火墙:入站-出站,规则
  • Stable Diffusion 告别复制关键词,高质量提示词自动生成插件
  • 【学习日记】【FreeRTOS】任务调度时如何考虑任务优先级——任务的自动切换
  • C语言暑假刷题冲刺篇——day3
  • Taro+vue3小程序开启分享他人和分享到朋友圈
  • JAVA-Spring中IOC容器是什么?
  • QT多屏显示程序
  • python使用xlwt时,报ValueError: More than 4094 XFs (styles)
  • GitHub 打不开解决方案
  • Java网络编程(一)网络基础
  • matlab使用教程(17)—多项式的定义和运算
  • 华为认证 | 这门HCIA认证正式发布!
  • 【Docker】Docker安装 MySQL 8.0,简洁版-快速安装使用
  • CSS自己实现一个步骤条
  • Visual Studio 2019 解决scanf函数报错问题
  • 亚马逊无限买家号如何注册?
  • 前端框架学习-ES6新特性(尚硅谷web笔记)
  • 普陀发布新规服务元宇宙企业 和数软件发展元宇宙场景落地
  • Kotlin差异化分析,let,run,with,apply及also
  • (stm32)低功耗模式
  • 【C++学习手札】一文带你认识C++虚函数(内层剖析)
  • Python“牵手”1688商品评论数据采集方法,1688API申请指南
  • “深入解析JVM内部机制:探秘Java虚拟机的奥秘“