这两天在写一个tr069的simulator,原理很简单啦,用httpclient模拟tr069的client端,发送soap message到我们的acs server.

发送soap message的代码如下:

public class MessageSender {
/**
* Logger for this class
*/
private static final Log logger = LogFactory.getLog(MessageSender.class);

private HttpClient httpClient;
private PostMethod postMethod;
private MessageFactory messageFactory;
private String url;
private NameValuePair sessionId;

public MessageSender(String ip){
this.httpClient = new HttpClient();

try {
this.messageFactory = MessageFactory.newInstance();
} catch (SOAPException e) {
logger.error(e.getMessage());
}

this.url = generateRequestUrl(ip);
}

private String generateRequestUrl(String ip) {
return "http://" + ip + ":8080/vantage/TR069";
}

public SOAPMessage sendMessage(SOAPMessage input) throws IOException, SOAPException {
this.postMethod = new PostMethod(this.url);
byte[] dataAsBytes = null;

if (input == null) {
logger.debug("Send a empty post");
dataAsBytes = new byte[0];
} else {

ByteArrayOutputStream data = new ByteArrayOutputStream();
input.writeTo(data);
dataAsBytes = data.toByteArray();
}

RequestEntity entity = new ByteArrayRequestEntity(dataAsBytes);
this.postMethod.setRequestEntity(entity);

if (this.sessionId != null) {
this.postMethod.addParameter(this.sessionId);
}

this.httpClient.executeMethod(this.postMethod);

sessionId = this.postMethod.getParameter("SessionID");

InputStream in = this.postMethod.getResponseBodyAsStream();

if (null == in) {
return null;
}

return this.messageFactory.createMessage(null, in);
}
}

最初的code里面,只有一个PostMethod,这样每次会一直keep一个http连接.因为在server端,只直接用http session来保存server的状态的,所以必须要是保持是一个session.用一个PostMethod可以做到这点.不过奇怪的是,在发第二次请求的时候,怎么都拿不到http connection.也不知道是不是httpclient的bug.后来才每次调用都重新create一个PostMethod,但是把第一次得到的sessionID add进去.