码迷,mamicode.com
首页 > 编程语言 > 详细

Spring RestTemplate: 比httpClient更优雅的Restful URL访问

时间:2016-09-23 15:02:01      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

{
  "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";
    }

 

Spring RestTemplate: 比httpClient更优雅的Restful URL访问

标签:

原文地址:http://www.cnblogs.com/tomcatandjerry/p/5899722.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!