springboot-24-restTemplate的使用
项目中使用的是HttpClient, 后来改成springboot, 偶然间发现restTemplate
- {
- "Author": "tomcat and jerry",
- "url":"http://www.cnblogs.com/tomcatandjerry/p/5899722.html"
- }
核心代码:
- String url = "http://localhost:8080/json";
- JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
实用:
restConfig.java
- package com.iwhere.scrapy.rest;
- import java.nio.charset.Charset;
- import java.util.Iterator;
- import java.util.List;
- 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.SimpleClientHttpRequestFactory;
- import org.springframework.http.converter.HttpMessageConverter;
- import org.springframework.http.converter.StringHttpMessageConverter;
- import org.springframework.web.client.RestOperations;
- import org.springframework.web.client.RestTemplate;
- /**
- * 定义restTemplate的配置
- *
- * @author wenbronk
- * @Date 下午4:33:35
- */
- @Configuration
- public class RestTemplateConfig {
- @Bean
- @ConditionalOnMissingBean({ RestOperations.class, RestTemplate.class })
- public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
- // return new RestTemplate(factory);
- RestTemplate restTemplate = new RestTemplate(factory);
- // 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为"ISO-8859-1")
- List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
- Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
- while (iterator.hasNext()) {
- HttpMessageConverter<?> converter = iterator.next();
- if (converter instanceof StringHttpMessageConverter) {
- iterator.remove();
- }
- }
- messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
- return restTemplate;
- }
- @Bean
- @ConditionalOnMissingBean({ClientHttpRequestFactory.class})
- public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
- SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
- factory.setReadTimeout(15000);// ms
- factory.setConnectTimeout(15000);// ms
- return factory;
- }
- }
请求测试:
- SpringRestTemplateApp.java
- @RestController
- @EnableAutoConfiguration
- @Import(value = {Conf.class})
- public class SpringRestTemplateApp {
- @Autowired
- RestTemplate restTemplate;
- /***********HTTP GET method*************/
- @RequestMapping("")
- public String hello(){
- String url = "http://localhost:8080/json";
- JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
- return json.toJSONString();
- }
- @RequestMapping("/json")
- public Object genJson(){
- JSONObject json = new JSONObject();
- json.put("descp", "this is spring rest template sample");
- return json;
- }
- /**********HTTP POST method**************/
- @RequestMapping("/postApi")
- public Object iAmPostApi(@RequestBody JSONObject parm){
- System.out.println(parm.toJSONString());
- parm.put("result", "hello post");
- return parm;
- }
- @RequestMapping("/post")
- public Object testPost(){
- String url = "http://localhost:8080/postApi";
- JSONObject postData = new JSONObject();
- postData.put("descp", "request for post");
- JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
- return json.toJSONString();
- }
- public static void main(String[] args) throws Exception {
- SpringApplication.run(SpringRestTemplateApp.class, args);
- }
- }
也可以异步调用
- @RequestMapping("/async")
- public String asyncReq(){
- String url = "http://localhost:8080/jsonAsync";
- ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
- future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {
- public void onSuccess(ResponseEntity<JSONObject> result) {
- System.out.println(result.getBody().toJSONString());
- }
- }, new FailureCallback() {
- public void onFailure(Throwable ex) {
- System.out.println("onFailure:"+ex);
- }
- });
- return "this is async sample";
自定义header
- @RequestMapping("/headerApi")//模拟远程的restful API
- public JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){
- System.out.println("headerApi====="+parm.toJSONString());
- Enumeration<String> headers = req.getHeaderNames();
- JSONObject result = new JSONObject();
- while(headers.hasMoreElements()){
- String name = headers.nextElement();
- System.out.println("["+name+"]="+req.getHeader(name));
- result.put(name, req.getHeader(name));
- }
- result.put("descp", "this is from header");
- return result;
- }
- @RequestMapping("/header")
- public Object postWithHeader(){
- //该方法通过restTemplate请求远程restfulAPI
- HttpHeaders headers = new HttpHeaders();
- headers.set("auth_token", "asdfgh");
- headers.set("Other-Header", "othervalue");
- headers.setContentType(MediaType.APPLICATION_JSON);
- JSONObject parm = new JSONObject();
- parm.put("parm", "1234");
- HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);
- HttpEntity<String> response = restTemplate.exchange(
- "http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string
- return response.getBody();
- }
springboot-24-restTemplate的使用的更多相关文章
- SpringBoot系列: RestTemplate 快速入门
====================================相关的文章====================================SpringBoot系列: 与Spring R ...
- SpringBoot 使用 RestTemplate 调用exchange方法 显示错误信息
SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...
- SpringBoot使用RestTemplate基础认证
SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...
- SpringBoot使用RestTemplate 摘要认证
SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...
- SpringBoot使用RestTemplate
SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 设置pom引用 <?xml v ...
- Springboot 使用 RestTemplate
每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code spring web 项目提供的RestTemplate,使java访问url更方便, ...
- SpringBoot配置RestTemplate的代理和超时时间
application.properties: #代理设置 proxy.enabled=false proxy.host=192.168.18.233 proxy.port=8888 #REST超时配 ...
- springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)
使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...
- SpringBoot集成RestTemplate
先把原文列出来: springboot实战之常用http客户端整合 springboot2.0集成RestTemplate -----------开始------------ SpringBoot应用 ...
- springboot系列十二、springboot集成RestTemplate及常见用法
一.背景介绍 在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端.我们可以使用JDK原生的URLConnection.Apache的Http Client.N ...
随机推荐
- Linux内核分析第八周总结
第八章 进程的切换和系统的一般执行过程 进程调度与进程调度的时机分析 第一种分类: I/O密集型(I/O-bound):频繁的进行I/O,通常会花费很多时间等待I/O操作的完成 CPU密集型(CPU- ...
- github个人作业
信息学院本科生课程设计 题目 文件加密和解密 课程名称 面向对象程序设计课程设计 课程编号 X031749 所在专业 计算机科学与技术 所在班级 计科高职13-3 ...
- Failed to execute goal org.springframework.boot
报错 [ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.0.RELEASE:ru ...
- #Leetcode# 977. Squares of a Sorted Array
https://leetcode.com/problems/squares-of-a-sorted-array/ Given an array of integers A sorted in non- ...
- js十大排序算法:冒泡排序
排序算法说明: (1)对于评述算法优劣术语的说明 稳定:如果a原本在b前面,而a=b,排序之后a仍然在b的前面:不稳定:如果a原本在b的前面,而a=b,排序之后a可能会出现在b的后面: 内排序:所有排 ...
- mysql的group_concat对应oracle的wm_concat
mysql的group_concat对应oracle的wm_concat http://bey2nd.blog.163.com/blog/static/12063183120124313360964/
- [转帖]Asp.Net MVC EF各版本区别
Asp.Net MVC EF各版本区别 https://www.cnblogs.com/liangxiaofeng/p/5840754.html 2009年發行ASP.NET MVC 1.0版 201 ...
- 自己站点的nginx 配置信息
user www www; worker_processes auto; error_log /home/wwwlogs/nginx_error.log crit; pid /usr/local/ng ...
- poj 3694 Network(割边+lca)
题目链接:http://poj.org/problem?id=3694 题意:一个无向图中本来有若干条桥,有Q个操作,每次加一条边(u,v),每次操作后输出桥的数目. 分析:通常的做法是:先求出该无向 ...
- python之datetime类
datetime.time时间类,一般用于显示当地时间 import datetime # 新建对象 datetime_obj = datetime.time(hour=12, minute=20, ...