Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header
{
"Author": "tomcat and jerry",
"url":"http://www.cnblogs.com/tomcatandjerry/p/5899722.html"
}
Spring RestTemplate, 使用java访问URL更加优雅,更加方便。
核心代码:
String url = "http://localhost:8080/json";
JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();
就这么简单,API访问完成了!
附上SpringBoot相关的完整代码:
RestTemplateConfig.java @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(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);
} }
===============================
另外还支持异步调用AsyncRestTemplate
@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";
}
================================
贴一段post请求如何自定义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();
}
Spring RestTemplate: 比httpClient更优雅的Restful URL访问, java HttpPost with header的更多相关文章
- Httpclient与RestTemplate的比较(比httpClient更优雅的Restful URL访问)
一.HttpClient (一)HttpClient 客户端 1.HttpClient 是 apache 的开源,需要引入两个包:httpclient-4.2.4.jar 和 httpcore-4.2 ...
- Spring RestTemplate介绍
http://www.cnblogs.com/rollenholt/p/3894117.html RestTemplate 这篇文章打算介绍一下Spring的RestTemplate.我这边以前设计到 ...
- Spring RestTemplate 专题
相同的参数(接口的入参json打印在日志了)在PostMan中返回预期的数据,但使用RestTemplate时去提示信息错误(参数中汉字).这种情况,搞得怀疑对RestTemplate的理解了使用Re ...
- Spring RestTemplate 的介绍和使用-入门
RestTemplate是什么? 传统情况下在java代码里访问restful服务,一般使用Apache的HttpClient.不过此种方法使用起来太过繁琐.spring提供了一种简单便捷的模板类来进 ...
- 如何更优雅地对接第三方API
本文所有示例完整代码地址:https://github.com/yu-linfeng/BlogRepositories/tree/master/repositories/third 我们在日常开发过程 ...
- Spring restTemplate
什么是RestTemplate RestTemplate是Spring提供的用于访问Rest服务的客户端,提供了多种便捷访问远程HTTP服务的方法,能够大大提高客户端的编写效率. 项目中注入Res ...
- Spring RestTemplate 小结
关于RestTemplate 首先,你可以把它理解为一个发起请求并接收响应的工具类(功能类似浏览器). 其次,它其实是一个壳,具体还是通过调用别的接口来实现(如jdk自带的连接,或者HttpClien ...
- git rebase VS git merge? 更优雅的 git 合并方式值得拥有
写在前面 如果你不能很好的应用 Git,那么这里为你提供一个非常棒的 Git 在线练习工具 Git Online ,你可以更直观的看到你所使用的命令会产生什么效果 另外,你在使用 Git 合并分支时只 ...
- Spring RestTemplate详解
Spring RestTemplate详解 1.什么是REST? REST(RepresentationalState Transfer)是Roy Fielding 提出的一个描述互联系统架构风格 ...
随机推荐
- PowerDesigner 逆向中 Name和Comment互换
在使用PowerDesigner对数据库进行概念模型和物理模型设计时,一般在NAME或Comment中写中文,在Code中写英文.Name用来显 示,Code在代码中使用,但Comment中的文字会保 ...
- DataTable自定义排序
使用JQ DataTable 的时候,希望某列数据可以进行自定义排序,操作如下:(以中文排序和百分比排序为例) 1:定义排序类型: //百分率排序 jQuery.fn.dataTableExt.oSo ...
- 未发现oracle(tm)客户端和网络组件
环境:Win7 64位.Oracle 11g 64位.PowerDesigner16.5.instant client12_1 64位. 在用PowerDesigner逆向数据库结构时,配置Oracl ...
- {MBR}{Grub}win7+Linux恢复MBR
准备:win7安装盘,Linux安装盘 Step1:在linux下查看一下硬盘的信息fdisk -l,找到hd0和ext分区的信息 Step2: 重启插入win7安装盘,对windows系统恢复Gru ...
- Linux文件查找
Linux下查找文件的命令有两个; locate: find : locate这个命令对其生成的数据库进行遍历(生成数据库的命令:updatedb),这一特性决定了查 找文件速度很快,但是locate ...
- 基于log4net的支持动态文件名、按日期和大小自动分割文件的日志组件
最近处理一个日志功能,用log4net的配置不能完全满足要求,所以在其基础上简单封装了一下,支持以下功能: 1 零配置 内置默认配置,引用dll后不需要添加或修改任何配置文件也可以使用 2 动态指定文 ...
- Backbone入门讲解
Backbone是一个实现了web前端mvc模式的js框架. 一种解决问题的通用方法,我们叫做模式. 设计模式:工厂模式,适配器模式,观察者模式等,推荐js设计模式这本书.设计模式是一种思想. 框架模 ...
- The CLR's Thread Pool
We were unable to locate this content in zh-cn. Here is the same content in en-us. .NET The CLR's Th ...
- java命名规范有感
一. 注()里的内容是自己的吐槽 二. 命名规约 不能以下划线或美元符开始和结尾.反例:_name,$name,name_,name$.(我就从来没这样用过) 不能使用拼音和英文组合方式命名.更不能以 ...
- R常见的几种常见统计图
1,向日葵散点图 2,热图 (颜色越深,数值越大) 3,折线图(散点图),绘制散点图集用 paris(data.frame)