java客户端通过AMFConnection类调用远程服务

若想直接用java来访问BlazeDS后台的服务,可以用BlazeDS中的AMFConnection类。这个类在3.1.0.2602版本上才有。
AMFConnection支持HTTP和HTTS, 并会自动记录cookie

一、 基本的使用
final String URL = "http://127.0.0.1/project-web/messagebroker/amf";
AMFConnection connection = new AMFConnection();
try {
    connection.connect(URL);
    User user = getUserFromSomewhere();
    connection.call("userService.createUser", user);
} catch (Exception e) {
    e.printStackTrace();
    throw e;
} finally {
    connection.close();

}
二、 AMFConnection连接过程
1. 建立连接、设置请求头及初始化请求环境
建立连接
URL raw = new URL(url);
urlConnection = (HttpURLConnection)urlObject.openConnection();
urlConnection.setDoOutput(true);

设置cookie和请求头
 
--setHttpRequestCookieHeader(); cookies to request
--httpRequestHeaders 设置时urlConnection的requestProperty
--Content-Type ->application/x-amf

设置请求环境:
actionContext = new ActionContext();

2. 发起请求
根据请求的命令和参数发出请求、按AMF3协议写入流、解析cookie, 按AMF解析返回流、返回结果
重要的方法是:
call(String command, Object ... arguments)

发出请求:
//构建请求信息(0-amf0 3-amf3)
ActionMessage requestMessage = new ActionMessage(getObjectEncoding());
MessageBody amfMessage = new MessageBody(command, responseURI, arguments);
requestMessage.addBody(amfMessage);
// Setup for AMF message serializer
actionContext.setRequestMessage(requestMessage);
ByteArrayOutputStream outBuffer = new ByteArrayOutputStream();
AmfMessageSerializer amfMessageSerializer = new AmfMessageSerializer();
amfMessageSerializer.initialize(serializationContext, outBuffer, amfTrace)
amfMessageSerializer.writeMessage(requestMessage);
outBuffer.writeTo(outputStream);
outBuffer.flush();
outBuffer.close();


解析返回流:
 
urlConnectionInputStream = new BufferedInputStream(inputStream);
// Mark the first 2 bytes so that the stream can be reset in case it
// contains non-AMF data.
urlConnectionInputStream.mark(2);
ActionMessage message = new ActionMessage();
actionContext.setRequestMessage(message);
MessageDeserializer deserializer = new AmfMessageDeserializer();
deserializer.initialize(serializationContext, urlConnectionInputStream, amfTrace);
deserializer.readMessage(message, actionContext);
Object result = null;
for (MessageBody msg : (ArrayList<MessageBody>)message.getBodies())
{
    String targetURI = msg.getTargetURI();

    if (targetURI.endsWith(MessageIOConstants.RESULT_METHOD))
    {
    	result =  msg.getData();
    }
    else if (targetURI.endsWith(MessageIOConstants.STATUS_METHOD))
    {
        String exMessage = "Server error";
        result = exMessage;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值