java client调用BlazeDS服务

若想直接用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;
    }
}


你可能感兴趣的:(java,Web)