每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code

spring web 项目提供的RestTemplate,使java访问url更方便,更优雅。

它是spring提供的异步的客户端http访问的核心class,它提供非常简单的RESTful方式与http server端进行数据交互,根据所提动的URLs进行http访问,并处理返回结果。它是基于JDK HTTP connection建立的。因此他可以使用不同的HTTP库(apache,netty and OkHttp)来setRequestFactory。

它实现了以下6个主要的HTTP meshod:

HTTP method RestTemplate methods
DELETE delete
GET getForObject,getForEntity
HEAD headForHeaders
OPTIONS optionsForAllow
PUT put
any exchange,execute

现简单介绍在Springboot中使用RestTemplate

首先在代码中加入RestTemplate的配置类

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.web.client.RestTemplate; /**
* Created by liuxu on 2017/12/22.
* RestTemplate配置类
*/
@Configuration
public class RestTemplateConfig { @Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
} @Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(5000);//单位为ms
factory.setConnectTimeout(5000);//单位为ms
return factory;
}
}

然后在需要访问url的类中注入RestTemplate

@Autowired
private RestTemplate restTemplate;

使用RestTemplate发送get请求

//get json数据
JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();

使用RestTemplate发送post请求

//post json数据
JSONObject postData = new JSONObject();
postData.put("data", "request for post");
JSONObject json = restTemplate.postForEntity(url, postData, JSONObject.class).getBody(); //对基本类型的解析 JSONObject obj =
json ;
System.out.println("name:" + obj.getString("name")); 
System.out.println("sex:" + obj.getString("sex"));
System.out.println("age" + obj.getInt("age"));
System.out.println("is_student" + obj.getBoolean("is_student"));
//对数组的解析
JSONArray hobbies = obj.getJSONArray("hobbies");
System.out.println("hobbies:");
for (int i = 0; i < hobbies.length(); i++) { String s = (String) hobbies.get(i); System.out.println(s); }

设置请求头

//post json string data
//return string
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
headers.setContentType(type);
headers.add("Accept", MediaType.APPLICATION_JSON.toString());
JSONObject jsonObj = JSONObject.parseObject(paras);
HttpEntity<String> formEntity = new HttpEntity<String>(jsonObj.toString(), headers);
String result = restTemplate.postForObject(url, formEntity, String.class);

每天学习一点点 编程PDF电子书、视频教程免费下载:
http://www.shitanlife.com/code

Springboot 使用 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的代理和超时时间

    application.properties: #代理设置 proxy.enabled=false proxy.host=192.168.18.233 proxy.port=8888 #REST超时配 ...

  7. springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)

    使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...

  8. SpringBoot集成RestTemplate

    先把原文列出来: springboot实战之常用http客户端整合 springboot2.0集成RestTemplate -----------开始------------ SpringBoot应用 ...

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

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

随机推荐

  1. 二维码编码与解码类库ThoughtWorks.QRCode

    官方地址:https://www.codeproject.com/Articles/20574/Open-Source-QRCode-Library 有源代码和示例程序 支持二维码编码(生成)和解码( ...

  2. Python入门到精通学习书籍推荐!

    1.Python基础教程(第2版 修订版)<Python基础教程(第2版修订版)>包括Python程序设计的方方面面,内容涉及的范围较广,既能为初学者夯实基础,又能帮助程序员提升技能,适合 ...

  3. [android] 调用系统照相机和摄像机

    查看系统照相机源码,找到清单文件查看 查看意图过滤器,action是android.media.action.IMAGE_CAPTURE category是android.intent.categor ...

  4. 了解java虚拟机—在TALB上分配对象(10)

    由于对象一般会分配在堆上,而堆是全局共享的.因此在同一时间,可能有多个线程在堆上申请空间.每次对象分内都必须要进行同步,因此TLAB这种线程专属的区域来避免多线程冲突.TLAB本身占用了eden区的空 ...

  5. 最长子串(FZU2128)

    最长子串 Time Limit:3000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u Submit Status  ...

  6. Linux常用基本命令:三剑客命令之-awk内置函数用法

    awk的内置函数大致可以分类为算数函数.字符串函数.时间函数.其他函数等 算数函数 最常用的算数函数有rand函数.srand函数.int函数. 可以使用rand函数生成随机数,但是使用rand函数时 ...

  7. jsp使用servlet实现文件上传

    1.在index.jsp中写入以下代码 <form method="post" action="demo3" enctype="multipar ...

  8. InheritParasitic.js

    // 寄生式继承 // 其基本思路是类似创建对象时的工厂模式,将继承过程封装在一个函数里,然后返回一个对象 function createObject(o){ var clone = Object.c ...

  9. Python sys 模块

    import sys # 把命令行参数返回一个 List,第一个元素是程序本身的路径 print(sys.argv) # 命令行运行 python3 sys_model.py klvchen hell ...

  10. Python爬虫html解析工具beautifulSoup在pycharm中安装及失败的解决办法

    1.安装步骤: 首先,你要先进入pycharm的Project Interpreter界面,进入方法是:setting(ctrl+alt+s) ->Project Interpreter,Pro ...