這兩天在寫(xiě)一個(gè)tr069的simulator,原理很簡(jiǎn)單啦,用httpclient模擬tr069的client端,發(fā)送soap message到我們的acs server.

發(fā)送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里面,只有一個(gè)PostMethod,這樣每次會(huì)一直keep一個(gè)http連接.因?yàn)樵趕erver端,只直接用http session來(lái)保存server的狀態(tài)的,所以必須要是保持是一個(gè)session.用一個(gè)PostMethod可以做到這點(diǎn).不過(guò)奇怪的是,在發(fā)第二次請(qǐng)求的時(shí)候,怎么都拿不到http connection.也不知道是不是httpclient的bug.后來(lái)才每次調(diào)用都重新create一個(gè)PostMethod,但是把第一次得到的sessionID add進(jìn)去.