上一篇文章中我们介绍了JCO3连接SAP的配置,本篇博客我们将介绍如何用jco来连接sap rfc接口,并提供一种统一的模板来对不同的sap接口进行调用。
注:输入参数为JSON字符串。
流程:发送http请求(HTTP+JSON)-->MULE ESB拿着接收到的报文用JCO3去调用RFC接口。
直接上代码。
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import com.sap.conn.jco.JCoDestination;
import com.sap.conn.jco.JCoFunction;
import com.sap.conn.jco.JCoParameterList;
import com.sap.conn.jco.JCoTable;
/**
* @author Lida json to rfc
*/
public class Json2Rfc {
public static String json2rfc(JSONObject jsonObject, String funcName) {
JCoDestination destination = SAPConn.connect();
JCoFunction function = null;
String result="";
try {
function = destination.getRepository().getFunction(funcName);
JCoParameterList input = function.getImportParameterList();
// 解析json
for (Object k : jsonObject.keySet()) {
Object v = jsonObject.get(k);
// 如果内层是数组,则对应表参数
if (v instanceof JSONArray) {
JSONArray jsonArray=JSONArray.fromObject(v);
JCoTable jCoTable=function.getTableParameterList().getTable((String)k);
for(Object object:jsonArray){//遍历数组
JSONObject jsObject=JSONObject.fromObject(object);
jCoTable.appendRow();//数组中每个元素添加一个行项目。
for (Object ak : jsObject.keySet()) {//遍历数组中元素的全部属性
Object av = jsObject.get(ak);
if(JSONNull.getInstance()!=av&&null!=av&&!av.equals(""))
jCoTable.setValue(ak.toString(), av.toString());
}
}
} else {
input.setValue((String)k, v);
}
}
function.execute(destination);
JCoParameterList pexport = function.getExportParameterList();
JCoParameterList texport = function.getTableParameterList();
String pstring=Xml2Json.xml2JSON(pexport.toXML());
String tstring=Xml2Json.xml2JSON(texport.toXML());
} catch (Exception e) {
}
······
return result;
}
}