项目中使用的是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. #个人博客作业week3——微软必应词典的使用

    产品的调研和评测 笔者使用的是win8的必应词典客户端. 首先打开客户端,用户界面的设计十分简洁,使用方便.但是词典主页与大多外语软件的设计相仿,例如有每日一句,每日阅读等模块,并没有令人感到新奇的地 ...

  2. 实训十二(stick的设定)

    上篇我们介绍到人物主角的设定,其实人物是有工具使的,那就是——stick小棍. 信息的获取.起始位置.长度的加载.边界的判断.位置.长度重置是需要我们主要考虑的问题 信息获取上考虑的使什么时候加载st ...

  3. 第一次Spring总结

    第一阶段:下载了类似app使用,并做了对比,分析,对自己的app有了一些构思,完成了环境的配置.在这一阶段,一开始只有两个女生显得有点弱,面对从未接触过的app项目,首先就是配置环境方面的,在经过班上 ...

  4. how-is-docker-different-from-a-normal-virtual-machine[Docker与VirtualMachine的区别]

    https://stackoverflow.com/questions/16047306/how-is-docker-different-from-a-normal-virtual-machine 被 ...

  5. 如何批量删除Docker中已经停止的容器

    如何批量删除Docker中已经停止的容器   方法一: #显示所有的容器,过滤出Exited状态的容器,取出这些容器的ID, sudo docker ps -a|grep Exited|awk '{p ...

  6. VMware安装win7提示 operating system not found

    在虚拟机上安装win7时,进度条读完,重启后提示operating system not found,可能原因是在使用分区工具格式化时没有把C盘设置为主分区并激活. 解决办法: 进入PE或者使用分区工 ...

  7. FOJ有奖月赛-2016年8月(daxia专场之过四题方有奖)

    http://acm.fzu.edu.cn/contest/list.php?cid=152 主要是a题, lucas定理, 就这一版能过..  记录一下代码, 另外两个最短路  一个模拟,没什么记录 ...

  8. XE2 运行时 item not found的解决办法

    .net类库的原因. 将C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG下面的 machine.config.default 改名为machin ...

  9. Java之数组遍历

    package basic; //数组遍历方法 public class ForEach { public static void main(String[] args) { // 原始数组 Stri ...

  10. Bootstrap面板

    前面的话 面板(Panels)是Bootstrap框架新增的一个组件,某些时候可能需要将某些 DOM 内容放到一个盒子里.对于这种情况,可以使用面板组件.本文将详细介绍Bootstrap面板 基础面板 ...