TZ_12_Spring的RestTemplate
2024-10-20 21:01:44
1.Http客户端工具
HttpClient:HttpClient是Apache公司的产品,是Http Components下的一个组件。
特点:
基于标准、纯净的Java语言。实现了Http1.0和Http1.1
以可扩展的面向对象的结构实现了Http全部的方法(GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE)
支持HTTPS协议。
通过Http代理建立透明的连接。
- 自动处理Set-Cookie中的Cookie。
2这个接口返回一个User对象,但我们实际的到是一个User的Json字符串需要我,们手动的转为User对象 此时就可以借助Spring的RestTemplate
@Test
public void testGetPojo() throws IOException {
HttpGet request = new HttpGet("http://localhost/hello");
String response = this.httpClient.execute(request, new BasicResponseHandler());
System.out.println(response);
}
3.Spring的RestTemplate
Spring提供了一个RestTemplate模板工具类,对基于Http的客户端进行了封装,并且实现了对象与json的序列化和反序列化,非常方便。RestTemplate并没有限定Http的客户端类型,而是进行了抽象,目前常用的3种都有支持:
1>HttpClient
2>OkHttp
3>JDK原生的URLConnection(默认的)
4.在启动类位置注册:
@Bean
public RestTemplate restTemplate() { return new RestTemplate();
}
在测试类中直接@Autowired
注入:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = HttpDemoApplication.class)
public class HttpDemoApplicationTests { @Autowired
private RestTemplate restTemplate; @Test
public void httpGet() {
User user = this.restTemplate.getForObject("http://localhost:8080/User/1.html", User.class);
System.out.println(user);
} }
最新文章
- html5第二天
- C#设计模式系列:原型模式(Prototype)
- Android Studio--Gradle基础(转)
- 使用audio标签播放音频文件
- java开发前奏
- datagridview添加复选框全选和取消
- linux matplotlib入门
- Java Socket编程readLine返回null,read返回-1的条件
- 【转】第一次使用Android Studio时你应该知道的一切配置
- 《APUE》第6章练习1
- FIO工具常用参数
- CodeForces 450
- 关闭窗口(window.close)
- JS判断是不是Decimal类型(正则实现)
- SQLSERVER清空(Truncate)被外键引用的数据表
- WebForm 文件上传
- 将Word表格中单元格中的文字替换成对应的图片
- 2、自动化运维之SaltStack远程执行详解
- 仿照selalchemy实现简单的mongo查询
- 最小可用id
热门文章
- [Vue warn]: Failed to mount component: template or render function not defined. 错误解决方法
- Cutting Game
- js把时间转化为 ‘2019-07-01’ 格式
- Ignite-Spark
- leetcode146周赛-1130-叶值的最小代价生成树*
- barrel shifter, logarthmic shifter and funnel shifter
- Apache服务器中运行CGI程序的方法,文中以Perl脚本作为示例
- 学习笔记 css样式
- lvs + keepalived + nginx + tomcat高可用负载反向代理服务器配置(一) 简介
- Apollo Lake设计缺陷,避免使用它们