项目主页: https://github.com/shopex/prism-java/
实现shopex Prism 的Java版SDK供第三方使用
JDK6或者更高版本
git clone https://github.com/hashio/websocket-client.git
cd websocket-client
mvn clean install
git clone https://github.com/ShopEx/prism-java.git
cd prism-java
mvn clean install
<dependency>
<groupId>cn.shopex</groupId>
<artifactId>prism-sdk</artifactId>
<version>1.0</version>
</dependency>
String url = "http://dilbmtcv.apihub.cn/api";
String key = "buwb2lii";
String secret = "ucr72ygfutspqeuu6s36";
PrismClient prismClient = new PrismClient(url,key,secret);
//api请求PATH路径
String methodPath = "/platform/notify/write";
Map<String,String> appParams = new HashMap<String, String>();
//添加API请求所需的应用级参数
appParams.put("data","hello world");
//发送POST请求
String apiResult = prismClient.doPost(methodPath, appParams);
System.out.println(apiResult);
//api请求PATH路径
String methodPath = "/platform/notify/status";
Map<String,String> appParams = new HashMap<String, String>();
//发送GET请求
String apiResult = prismClient.doGet(methodPath,appParams);
System.out.println(apiResult);
prismClient.setPrismMsgHandler(new PrismMsgHandler() {
//Websocket连接完成时触发调用
@Override
public void onOpen(WebSocket socket) {
System.out.println("---> open");
}
//接受到Websocket服务端信息时触发调用
@Override
public void onMessage(WebSocket socket, PrismMsg prismMsg) {
System.out.println("---> receive msg:"+prismMsg);
if (prismMsg.getTag() == 1) {//这里只对第一条消息做ACK应答
try {
socket.send(prismClient.assembleAckData(prismMsg.getTag()));
System.out.println("发送ACK完成:"+prismMsg.getTag());
} catch (WebSocketException e) {
e.printStackTrace();
}
}
}
//Websocket发生异常时触发调用
@Override
public void onError(WebSocket socket, WebSocketException e) {
e.printStackTrace();
System.out.println("---> error:"+e);
}
//Websocket连接关闭时触发调用
@Override
public void onClose(WebSocket socket) {
System.out.println("---> close");
}
});
prismClient.executeNotify();
prismClient.publish("order.new","hello world");
prismClient.consume();
prismClient.ack(1);
详细使用请代码点击这里
prismClient.requireOauth(request,response);//启动oauth认证
我们以spring mvc为框架的web项目为例,下面的代码在用户登录时会启动oauth认证,SDK会检查session中是否存在session_id,如果不存在则跳转到oauth页面, 完成登录后会回跳回来。 完成登录后会将当前登录信息session_id设置到session中
@Controller
@RequestMapping("/user")
public class LoginController {
@Resource
private PrismClient prismClient;
//测试oauth授权
@RequestMapping("/login")
public ModelAndView login(HttpServletRequest request,HttpServletResponse response) {
ModelAndView view = new ModelAndView("/index");
prismClient.requireOauth(request,response);
return view;
}
}
如果授权过期,可以调用refreshToken()
方法来刷新授权令牌
详细代码可以在源码测试下查看,先进入Main启动web容器,然后浏览器打开登录页面localhost:8002/user/login 即可测试Oauth认证