项目中使用的是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的使用的更多相关文章

  1. SpringBoot系列: RestTemplate 快速入门

    ====================================相关的文章====================================SpringBoot系列: 与Spring R ...

  2. SpringBoot 使用 RestTemplate 调用exchange方法 显示错误信息

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  3. SpringBoot使用RestTemplate基础认证

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  4. SpringBoot使用RestTemplate 摘要认证

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 SpringBoot使用RestTe ...

  5. SpringBoot使用RestTemplate

    SpringBoot使用RestTempate SpringBoot使用RestTemplate摘要认证 SpringBoot使用RestTemplate基础认证 设置pom引用 <?xml v ...

  6. Springboot 使用 RestTemplate

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code spring web 项目提供的RestTemplate,使java访问url更方便, ...

  7. SpringBoot配置RestTemplate的代理和超时时间

    application.properties: #代理设置 proxy.enabled=false proxy.host=192.168.18.233 proxy.port=8888 #REST超时配 ...

  8. springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)

    使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...

  9. SpringBoot集成RestTemplate

    先把原文列出来: springboot实战之常用http客户端整合 springboot2.0集成RestTemplate -----------开始------------ SpringBoot应用 ...

  10. springboot系列十二、springboot集成RestTemplate及常见用法

    一.背景介绍 在微服务都是以HTTP接口的形式暴露自身服务的,因此在调用远程服务时就必须使用HTTP客户端.我们可以使用JDK原生的URLConnection.Apache的Http Client.N ...

随机推荐

  1. #科委外文文献发现系统——导出word模板1.0

    ps:该篇文档由实验室ljg提供. Crowdsourcing 一.             技术简介 Crowdsourcing, a modern business term coined in ...

  2. iOS Runloop理解

    一.RunLoop的定义 当有持续的异步任务需求时,我们会创建一个独立的生命周期可控的线程.RunLoop就是控制线程生命周期并接收事件进行处理的机制. RunLoop是iOS事件响应与任务处理最核心 ...

  3. 【转】GPS定位准确度CEP、RMS

    转自:http://blog.sina.com.cn/s/blog_70f96fda0101lcb9.html CEP和RMS是GPS的定位准确度(俗称精度)单位,是误差概率单位.就拿2.5M CEP ...

  4. Flask-论坛开发-3-数据库

    对Flask感兴趣的,可以看下这个视频教程:http://study.163.com/course/courseLearn.htm?courseId=1004091002 1. SQLAlchemy ...

  5. MySQLi面向对象实践--insert、update、delete

    执行insert <?php $mysqli = new Mysqli(); $mysqli->connect("localhost","root" ...

  6. Linux列举所有隐藏文件

    ll 命令是 ls -l的缩写 ls -a是列举所有(all)文件,包含隐藏文件,以.开头的文件. ls -l是以列表(list)方式列举文件. http://bbs.chinaunix.net/th ...

  7. PP生产订单成本的计划、控制和结算

    SAP系统成本分析功能关注订单的成本,通过对计划成本和实际成本的比较分析,可以发现成本控制上的问题,以便及时解决问题.1.订单成本计划在基础数据齐全的基础上,系统可以自动滚算生产订单的成本.生产订单计 ...

  8. js控制浏览器全屏

    HTML 5中的full screen,目前可以在除IE和opera外的浏览器中使用 ,有的时候用来做全屏API,游戏呀,等都很有用.先看常见的API element.requestFullScree ...

  9. 反编译微信小程序

    最近看了个微信小程序古诗词全集,想知道他的前后端是怎么实现的,所以就想到了反编译.小程序安装后会有个wxapkg格式的文件存在/data/data/com.tencent.mm/MicroMsg/** ...

  10. python的数据相关框架

    ipython 多种编程语言之间进行交互计算的命令行shell graphlab greate 快速构建大型高性能数据产品 pandas 数据分析 pulp 线性编程模型 matplotlib sci ...