项目中一直使用的就是这部分源码。字符集是utf-8,xml报文格式,需要在报文头拼上字节长度。传输方式是字节流。发出来,与大家共勉。
public static Map queryESB(String xml) throws Exception {
StringBuilder errorMsg = new StringBuilder();
Map bodymap = new HashMap();
Map<String, String> proMap = PropertiesUtil.buildproperties();
String ip = proMap.get("ip");
int port = Integer.parseInt(proMap.get("port"));
String responseMessage = "";
Socket socket = null;
try {
socket = new Socket(ip, port);
socket.setSoTimeout(60 * 1000);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(xml.getBytes("UTF-8"));
out.flush();
byte[] header = new byte[8];
int headerLength = in.read(header);
String charset = "UTF-8";
String headerInfo = "";
int length = 0;
byte[] body;
if (headerLength != 8) {
errorMsg.append("报文长度字节不足8位!"+headerLength);
} else {
headerInfo = new String(header, charset);
length = Integer.parseInt(headerInfo.trim());
body = new byte[length];
int off = 0;
while (true) {
int ret = in.read(body, off, body.length - off);
if (ret <= 0) {
break;
}
off += ret;
}
responseMessage = new String(body, charset);
System.out.println("返回报文:"+responseMessage);
}
} catch (Exception e) {
errorMsg.append("发送失败!"+e);
System.out.println("ESB request is fail");
} finally {
try {
socket.close();
} catch (IOException e) {
errorMsg.append("客户端关闭socket异常!");
}
}
if (errorMsg.length() == 0) {
bodymap = resolveXML(errorMsg, responseMessage);
}
return bodymap;
}