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

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. {  
  2.   "Author""tomcat and jerry",  
  3.   "url":"http://www.cnblogs.com/tomcatandjerry/p/5899722.html"      
  4. }  

spring RestTemplate, 使用Java访问URL更加优雅,更加方便。

核心代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. String url = "http://localhost:8080/json";  
  2. JSONObject json = restTemplate.getForEntity(url, JSONObject.class).getBody();  

就这么简单,API访问完成了!

附上SpringBoot相关的完整代码:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. RestTemplateConfig.java  
  2.   
  3. @Configuration  
  4. public class RestTemplateConfig{  
  5.     @Bean  
  6.     public RestTemplate restTemplate(ClientHttpRequestFactory factory){  
  7.         return new RestTemplate(factory);  
  8.     }  
  9.       
  10.     @Bean  
  11.     public ClientHttpRequestFactory simpleClientHttpRequestFactory(){  
  12.         SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();  
  13.         factory.setReadTimeout(5000);//ms  
  14.         factory.setConnectTimeout(15000);//ms  
  15.         return factory;  
  16.     }  
  17. }  

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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. }  

===============================

另外还支持异步调用AsyncRestTemplate

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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";  
  15.     }  

 ================================

贴一段post请求如何自定义header

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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.     }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值