看到了 http://www.iteye.com/topic/1121252,
以前也开发了个简单的开放api系统, 总共用了10个左右的类就可以搞定(使用spring mvc).现在把代码整理下发出.
2. 我们最重要的要求是: 简单开发,简单使用, Service要写的干干净净,让开发API的coder在开发一个API的时候不用学习任何额外的东西, 而是在写一个普通的企业应用里面的Service(or Manager)代码, 下面就是开发一个API的步骤
1)定义API接口
package ws.service; import ws.annotation.HttpWebService; import ws.annotation.Path; import ws.service.impl.Hello; @HttpWebService public interface HelloService { @Path(value = "/heloWorld", paramNames = "name") Hello helloWorld2(String name); @Path(value = "/test") void test(); @Path(value = "/exception") void exception(); }
2.API实现
package ws.service.impl; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import ws.service.HelloService; public class HelloServiceImpl implements HelloService { private static Log log = LogFactory.getLog(HelloServiceImpl.class); public HelloServiceImpl() { log.debug("Hello service init!!!"); } @Override public Hello helloWorld2(String name) { return new Hello(name); } @Override public void test() { log.debug("test"); } @Override public void exception() { if(1==1) { throw new RuntimeException("error"); } } }
3.Spring配置
<bean id="hello" class="ws.service.impl.HelloServiceImpl"/>
这样我们就已经定义了3个API了.分别是 /heloWorld ,/test ,/exception
下面看调用, 直接使用浏览器,
完整代码已经放在
https://github.com/yangjk/http-web-service
上面只是一个简单示例, 保证API的访问安全性代码问题稍后添加,
是实现方式添加interceptor.
1.授权校验
2.hmac校验(对称、非对称)
3.防重放攻击
4.超时控制
5.审计
实现方式参照
http://www.thebuzzmedia.com/designing-a-secure-rest-api-without-oauth-authentication/
未完待续.