项目中使用的是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. Mooc总结——Linux内核分析

    朱荟潼+ 原创作品转载请注明出处 :<Linux内核分析>MOOC课程http://mooc.study.163.com/course/USTC-1000029000 学习笔记链接汇总 第 ...

  2. jeecg的下拉列表

    jeecg里面下拉列表的使用 ①建立数据字典seo_id <t:dictSelect field="operationPromotionAccount" typeGroupC ...

  3. Daily Scrum- 12/28

    Meeting Minutes 讨论alpha 的feed back; 决定添加按钮向下的动作,作为feature; 完成了界面的微调,开始使用alpha.1进行feed back的收集 Burndo ...

  4. MyBatis 返回类型resultType为map时的null值不返回问题

    问题一:    查询结果集中 某字段 的值为null,在map中不包含该字段的key-value对 解决:在mybatis.xml中添加setting参数 <!-- 在null时也调用 sett ...

  5. 无符号整型 unsigned int、unsigned long、usigned long long、size_t 比较和格式控制

    位数比较 由于数据的长度和平台相关,所以基于 64 位系统比较. Windows Linux unsigned int 32 bits/4294967295 32 bits unsigned long ...

  6. vue原理探索--响应式系统

    Vue.js 是一款 MVVM 框架,数据模型仅仅是普通的 JavaScript 对象,但是对这些对象进行操作时,却能影响对应视图,它的核心实现就是「响应式系统」. 首先看一下 Object.defi ...

  7. linux 十个命令

    http://www.roncoo.com/article/detail/124514

  8. bram和dram的区别

    http://blog.csdn.net/jbb0523/article/details/6533760

  9. iOS 页面之间的转场动画控制器间的转换

    CATransition类实现层的转场动画.你可以从一组预定义的转换或者通过提供定制的CIFilter实例来指定转场效果. 例如:控制器之间的跳转 LoginViewController *myVC ...

  10. BZOJ2959长跑——LCT+并查集(LCT动态维护边双连通分量)

    题目描述 某校开展了同学们喜闻乐见的阳光长跑活动.为了能“为祖国健康工作五十年”,同学们纷纷离开寝室,离开教室,离开实验室,到操场参加3000米长跑运动.一时间操场上熙熙攘攘,摩肩接踵,盛况空前. 为 ...