10个类搞定无任何侵入的开放API服务

1.简介 
   看到了 http://www.iteye.com/topic/1121252
   以前也开发了个简单的开放api系统, 总共用了10个左右的类就可以搞定(使用spring mvc).现在把代码整理下发出. 

2. 我们最重要的要求是: 简单开发,简单使用 , Service要写的干干净净,让开发API的coder在开发一个API的时候不用学习任何额外的东西, 而是在写一个普通的企业应用里面的Service(or Manager)代码, 下面就是开发一个API的步骤 
  1)定义API接口 

Java代码
  1. package ws.service;  
  2.   
  3.   
  4. import ws.annotation.HttpWebService;  
  5. import ws.annotation.Path;  
  6. import ws.service.impl.Hello;  
  7.   
  8. @HttpWebService  
  9. public interface HelloService {  
  10.   
  11.   
  12.     @Path(value = "/heloWorld", paramNames = "name")  
  13.     Hello helloWorld2(String name);  
  14.   
  15.     @Path(value = "/test")  
  16.     void test();  
  17.   
  18.     @Path(value = "/exception")  
  19.     void exception();  
  20.   
  21. }  

  2.API实现 
Java代码
  1. package ws.service.impl;  
  2.   
  3. import org.apache.commons.logging.Log;  
  4. import org.apache.commons.logging.LogFactory;  
  5. import ws.service.HelloService;  
  6.   
  7. public class HelloServiceImpl implements HelloService {  
  8.   
  9.     private static Log log = LogFactory.getLog(HelloServiceImpl.class);  
  10.   
  11.     public HelloServiceImpl() {  
  12.         log.debug("Hello service init!!!");  
  13.     }  
  14.   
  15.   
  16.     @Override  
  17.     public Hello helloWorld2(String name) {  
  18.         return new Hello(name);  
  19.     }  
  20.   
  21.     @Override  
  22.     public void test() {  
  23.        log.debug("test");  
  24.     }  
  25.   
  26.     @Override  
  27.     public void exception() {  
  28.         if(1==1) {  
  29.             throw new RuntimeException("error");  
  30.         }  
  31.     }  
  32.   
  33. }  

  3.Spring配置 
  
Xml代码
  1. <bean id="hello" class="ws.service.impl.HelloServiceImpl"/>  


这样我们就已经定义了3个API了.分别是 /heloWorld ,/test ,/exception  

  下面看调用, 直接使用浏览器, 

 

 

 

完整代码已经放在 

https://github.com/jqq/rest 

上面只是一个简单示例, 保证API的访问安全性代码问题稍后添加, 

是实现方式添加interceptor. 
1.授权校验 
2.hmac校验(对称、非对称) 
3.防重放攻击 
4.超时控制 
5.审计 

实现方式参照 
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/ 
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值