项目中使用的是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. ChangeSetenceSort(java)

    package com.home.test;       import java.util.Arrays;       public class ChangeSort {       public S ...

  2. 总结 推广app

    扫一扫二维码即可安装使用我们的app,方便快捷. 电脑端下载地址:http://pan.baidu.com/s/1bocWPPX http://a.app.qq.com/o/simple.jsp?pk ...

  3. 无限级结构SQL查询所有的下级和所有的下级

    Id,PId无限级结构,查询某个Id的所有下级或所有上级,使用WITH AS查询 查找Id为1所有的下级 /*查找Id为1所有的下级*/ WITH T AS( SELECT Id,PId,Name,0 ...

  4. Java Script正则表达式语法学习

    今天在做页面交互验证时,在HTML里面第一反应居然用了Java 处理正则表达式的语法... ---------------------------------题记 学习来源 http://www.ru ...

  5. HTML DOM 学习笔记

    一.HTML DOM定义了所有HTML元素的对象和属性,以及访问他们的方法即:HTML DOM是关于如何获取,修改,添加,删除HTML元素的标准二.DOM节点1.分类整个文档是一个文档节点每个HTML ...

  6. Maven:The parent project must have a packaging type of POM

    在Maven Project 执行 New Maven Modual时,提示错误:The parent project must have a packaging type of POM http:/ ...

  7. Java singleton 一例

    org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of ...

  8. C语言ODBC数据库操作

    今天我们来介绍一下C语言操作数据库的方法,这里我们使用的是ODBC方式.环境是WIN7+VC6.其他环境也差不多,具体情况具体分析. 首先是环境的配置以及数据源的添加.这里就不去解释了,相关资料网上有 ...

  9. [转帖]/etc/security/limits.conf的含义

    https://www.cnblogs.com/pzk7788/p/7250723.html /etc/security/limits.conf 是 Linux 资源使用配置文件,用来限制用户对系统资 ...

  10. BZOJ3129 SDOI2013方程(容斥原理+扩展lucas)

    没有限制的话算一个组合数就好了.对于不小于某个数的限制可以直接减掉,而不大于某个数的限制很容易想到容斥,枚举哪些超过限制即可. 一般情况下n.m.p都是1e9级别的组合数没办法算.不过可以发现模数已经 ...