Spring Web 项目提供的RestTemplate,使java访问url更方便,更优雅。
RestTemplate
是Spring
提供的异步的客户端Http访问的核心class,它提供非常简单的RESTful方式与HTTP Server端进行数据交互,根据所提动的URLs进行http访问,并处理返回结果。它是基于JDK HTTP connection建立的。因此他可以使用不同的HTTP库(apache,netty and OkHttp)来setRequestFactory。
它实现了以下6个主要的HTTP meshod:
它实现了以下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();
设置请求头
//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 formEntity = new HttpEntity(jsonObj.toString(), headers);
String result = restTemplate.postForObject(url, formEntity, String.class);
Spring RestTemplate: 比httpClient更优雅的Restful URL访问
实战;
{
"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 = {RestTemplateConfig.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> future = asyncRestTemplate.getForEntity(url, JSONObject.class);
future.addCallback(new SuccessCallback>() {
public void onSuccess(ResponseEntity result) {
System.out.println(result.getBody().toString());
}
}, 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 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 entity = new HttpEntity(parm, headers);
HttpEntity response = restTemplate.exchange(
"http://localhost:8080/headerApi", HttpMethod.POST, entity, String.class);//这里放JSONObject, String 都可以。因为JSONObject返回的时候其实也就是string
return response.getBody();
}