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

  1. {
  2. "Author": "tomcat and jerry",
  3. "url":"http://www.cnblogs.com/tomcatandjerry/p/5899722.html"
  4. }

核心代码:

  1. String url = "http://localhost:8080/json";
  2. JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();

实用:

restConfig.java

  1. package com.iwhere.scrapy.rest;
  2.  
  3. import java.nio.charset.Charset;
  4. import java.util.Iterator;
  5. import java.util.List;
  6.  
  7. import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.http.client.ClientHttpRequestFactory;
  11. import org.springframework.http.client.SimpleClientHttpRequestFactory;
  12. import org.springframework.http.converter.HttpMessageConverter;
  13. import org.springframework.http.converter.StringHttpMessageConverter;
  14. import org.springframework.web.client.RestOperations;
  15. import org.springframework.web.client.RestTemplate;
  16.  
  17. /**
  18. * 定义restTemplate的配置
  19. *
  20. * @author wenbronk
  21. * @Date 下午4:33:35
  22. */
  23. @Configuration
  24. public class RestTemplateConfig {
  25.  
  26. @Bean
  27. @ConditionalOnMissingBean({ RestOperations.class, RestTemplate.class })
  28. public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
  29. // return new RestTemplate(factory);
  30.  
  31. RestTemplate restTemplate = new RestTemplate(factory);
  32.  
  33. // 使用 utf-8 编码集的 conver 替换默认的 conver(默认的 string conver 的编码集为"ISO-8859-1")
  34. List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
  35. Iterator<HttpMessageConverter<?>> iterator = messageConverters.iterator();
  36. while (iterator.hasNext()) {
  37. HttpMessageConverter<?> converter = iterator.next();
  38. if (converter instanceof StringHttpMessageConverter) {
  39. iterator.remove();
  40. }
  41. }
  42. messageConverters.add(new StringHttpMessageConverter(Charset.forName("UTF-8")));
  43.  
  44. return restTemplate;
  45. }
  46.  
  47. @Bean
  48. @ConditionalOnMissingBean({ClientHttpRequestFactory.class})
  49. public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
  50. SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
  51. factory.setReadTimeout(15000);// ms
  52. factory.setConnectTimeout(15000);// ms
  53. return factory;
  54. }
  55. }

请求测试:

  1. SpringRestTemplateApp.java
  2. @RestController
  3. @EnableAutoConfiguration
  4. @Import(value = {Conf.class})
  5. public class SpringRestTemplateApp {
  6.  
  7. @Autowired
  8. RestTemplate restTemplate;
  9.  
  10. /***********HTTP GET method*************/
  11. @RequestMapping("")
  12. public String hello(){
  13. String url = "http://localhost:8080/json";
  14. JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
  15. return json.toJSONString();
  16. }
  17.  
  18. @RequestMapping("/json")
  19. public Object genJson(){
  20. JSONObject json = new JSONObject();
  21. json.put("descp", "this is spring rest template sample");
  22. return json;
  23. }
  24.  
  25. /**********HTTP POST method**************/
  26. @RequestMapping("/postApi")
  27. public Object iAmPostApi(@RequestBody JSONObject parm){
  28. System.out.println(parm.toJSONString());
  29. parm.put("result", "hello post");
  30. return parm;
  31. }
  32.  
  33. @RequestMapping("/post")
  34. public Object testPost(){
  35. String url = "http://localhost:8080/postApi";
  36. JSONObject postData = new JSONObject();
  37. postData.put("descp", "request for post");
  38. JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody();
  39. return json.toJSONString();
  40. }
  41.  
  42. public static void main(String[] args) throws Exception {
  43. SpringApplication.run(SpringRestTemplateApp.class, args);
  44. }
  45.  
  46. }

也可以异步调用

  1. @RequestMapping("/async")
  2. public String asyncReq(){
  3. String url = "http://localhost:8080/jsonAsync";
  4. ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
  5. future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {
  6. public void onSuccess(ResponseEntity<JSONObject> result) {
  7. System.out.println(result.getBody().toJSONString());
  8. }
  9. }, new FailureCallback() {
  10. public void onFailure(Throwable ex) {
  11. System.out.println("onFailure:"+ex);
  12. }
  13. });
  14. return "this is async sample";

自定义header

  1. @RequestMapping("/headerApi")//模拟远程的restful API
  2. public JSONObject withHeader(@RequestBody JSONObject parm, HttpServletRequest req){
  3. System.out.println("headerApi====="+parm.toJSONString());
  4. Enumeration<String> headers = req.getHeaderNames();
  5. JSONObject result = new JSONObject();
  6. while(headers.hasMoreElements()){
  7. String name = headers.nextElement();
  8. System.out.println("["+name+"]="+req.getHeader(name));
  9. result.put(name, req.getHeader(name));
  10. }
  11. result.put("descp", "this is from header");
  12. return result;
  13. }
  14.  
  15. @RequestMapping("/header")
  16. public Object postWithHeader(){
  17.     //该方法通过restTemplate请求远程restfulAPI
  18. HttpHeaders headers = new HttpHeaders();
  19. headers.set("auth_token", "asdfgh");
  20. headers.set("Other-Header", "othervalue");
  21. headers.setContentType(MediaType.APPLICATION_JSON);
  22.  
  23. JSONObject parm = new JSONObject();
  24. parm.put("parm", "1234");
  25. HttpEntity<JSONObject> entity = new HttpEntity<JSONObject>(parm, headers);
  26. HttpEntity<String> response = restTemplate.exchange(
  27. "http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string
  28. return response.getBody();
  29. }

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. Linux内核分析第八周总结

    第八章 进程的切换和系统的一般执行过程 进程调度与进程调度的时机分析 第一种分类: I/O密集型(I/O-bound):频繁的进行I/O,通常会花费很多时间等待I/O操作的完成 CPU密集型(CPU- ...

  2. github个人作业

    信息学院本科生课程设计 题目                    文件加密和解密 课程名称 面向对象程序设计课程设计 课程编号 X031749 所在专业 计算机科学与技术 所在班级 计科高职13-3 ...

  3. Failed to execute goal org.springframework.boot

    报错 [ERROR] Failed to execute goal org.springframework.boot:spring-boot-maven-plugin:1.4.0.RELEASE:ru ...

  4. #Leetcode# 977. Squares of a Sorted Array

    https://leetcode.com/problems/squares-of-a-sorted-array/ Given an array of integers A sorted in non- ...

  5. js十大排序算法:冒泡排序

    排序算法说明: (1)对于评述算法优劣术语的说明 稳定:如果a原本在b前面,而a=b,排序之后a仍然在b的前面:不稳定:如果a原本在b的前面,而a=b,排序之后a可能会出现在b的后面: 内排序:所有排 ...

  6. mysql的group_concat对应oracle的wm_concat

    mysql的group_concat对应oracle的wm_concat http://bey2nd.blog.163.com/blog/static/12063183120124313360964/

  7. [转帖]Asp.Net MVC EF各版本区别

    Asp.Net MVC EF各版本区别 https://www.cnblogs.com/liangxiaofeng/p/5840754.html 2009年發行ASP.NET MVC 1.0版 201 ...

  8. 自己站点的nginx 配置信息

    user www www; worker_processes auto; error_log /home/wwwlogs/nginx_error.log crit; pid /usr/local/ng ...

  9. poj 3694 Network(割边+lca)

    题目链接:http://poj.org/problem?id=3694 题意:一个无向图中本来有若干条桥,有Q个操作,每次加一条边(u,v),每次操作后输出桥的数目. 分析:通常的做法是:先求出该无向 ...

  10. python之datetime类

    datetime.time时间类,一般用于显示当地时间 import datetime # 新建对象 datetime_obj = datetime.time(hour=12, minute=20, ...