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

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

2. 我们最重要的要求是:[b][color=red]简单开发,简单使用[/color][/b], 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"/>


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

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

[img]http://dl.iteye.com/upload/attachment/0069/0372/72d96143-3fb0-3fa5-9caa-72488d193d85.jpg[/img]

[img]http://dl.iteye.com/upload/attachment/0069/0374/5464ac13-f362-39c2-9da6-c25b9d24dfbe.jpg[/img]

[img]http://dl.iteye.com/upload/attachment/0069/0376/0327ce78-1875-3044-90ae-5598cd165168.jpg[/img]

完整代码已经放在
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/

未完待续.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值