项目中使用的是HttpClient, 后来改成springboot, 偶然间发现restTemplate

原博客: http://blog.csdn.net/u013895412/article/details/53096855

{  "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);// msfactory.setConnectTimeout(15000);// msreturn 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调用Webservice接口

    1.基于Springboot整合RestTemplate调用Webservice接口,如果感觉使用webservice客户端调用服务器端不会,或者不方便 的时候,可以尝试使用RestTemplate来 ...

  2. SpringBoot系列: RestTemplate 快速入门

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

  3. SpringBoot (6)---RestTemplate方法详解(2)

    SpringBoot (6)---RestTemplate方法详解(2) 说明 上一篇SpringBoot 2.1 | 第三篇:RestTemplate请求HTTP(1)简单运用了RestTempla ...

  4. springBoot使用RestTemplate报错:No instance available for xxx.xxx.xxx.xxx

    springBoot使用RestTemplate报错:No instance available for xxx.xxx.xxx.xxx 解决方案:添加配置类 解决方案:添加配置类 @Configur ...

  5. springboot的RestTemplate客户端模式取得uaa的token

    springboot的RestTemplate客户端模式取得uaa的token @Scheduled(fixedRate = 5000) public String getAuthorize() {H ...

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

    application.properties: 1 #代理设置 2 proxy.enabled=false 3 proxy.host=192.168.18.233 4 proxy.port=8888 ...

  7. SpringBoot专栏:RestTemplate基本使用与微服务藕断丝连(终结-告别篇)

    有话要说 不善于言谈.不善笔墨.更不善交际..为何坚持写作? 虽如此,但是个人有一颗分享的心,有满腔的热情,更坚信只要坚持写作就能有所提升,就能受益于更多的人那就足够了. 未来又有何惧,编程之路需要小 ...

  8. springboot使用restTemplate post提交值 restTemplate post值

    post提交有 FormData和Payload  两种形式: 第一种是formdata形式,在header参数里可以直接看到 payload则封装成json格式post过去,获取以后需要再解析成实体 ...

  9. springboot集成restTemplate实现rest接口调用

    目录 一restTemplate简介 二restTemplate常用方法列表 2.1 get请求方法预览 2.2 post方法请求预览 2.3put请求方法预览 2.4 delete请求方法预览 2. ...

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

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

最新文章

  1. 【新无人机数据集】从 行人重识别 到 无人机目标定位
  2. 解决ORA-15097 Cannot shutdown ASM if OCR is Located in ASM
  3. 文献记录(part27)--A distance for belief functions of orderable set
  4. vue实现监听滚动条
  5. 文件的输入和输出:流和缓冲区的概念和文件操作函数总结
  6. linux 查看共享磁盘_如何可视化地查看 Linux 系统磁盘使用情况?
  7. python虚拟机 基于寄存器_基于栈虚拟机和基于寄存器虚拟机的比较
  8. nginx负载均衡?
  9. linux下Apache默认安装路径
  10. html5网页设计-表单
  11. iOS性能优化系列篇之“优化总体原则”
  12. Citrix提供免费阳春版XenServer
  13. 阿里巴巴集团2015年秋季校招在线笔试附加题分析
  14. 使用Tansformer分割三维腹部多器官--UNETR实战
  15. qt 动画 顺序 轮播图轮播图
  16. LAMP配置DISCUS
  17. 使用HTML5,CSS3和Jquery的老虎机效果
  18. 电脑安装软件时,如何避免捆绑安装?
  19. 中兴网络设备交换机路由器查看告警信息命令方法
  20. rsync同步的艺术

热门文章

  1. 【noiOJ】P1996
  2. 使用FIR.im发布自己的移动端APP
  3. jquery之stop()的用法
  4. FirstApp,iphone开发学习总结7,相机
  5. java 大臣的旅费_PREV-9-蓝桥杯-历届试题-大臣的旅费-java
  6. 神经网络与机器学习 笔记—时序模式、非线性滤波
  7. poj2186强联通(牛仰慕)
  8. C语言经典例35-字符串反转
  9. 【错误记录】jcenter 移除问题 ( Please remove usages of `jcenter()` Maven repository from your build scripts )
  10. 【错误记录】IntelliJ IDEA 中右键点击源码目录选择 New 选项 没有创建 Java Class 选项 ( 将对应的源码目录标记为 Sources 选项 )