首页 > 代码库 > Odoo(OpenERP)开发实践:通过XML-RPC接口訪问Odoo数据库

Odoo(OpenERP)开发实践:通过XML-RPC接口訪问Odoo数据库

Odoo(OpenERP)server支持通过XML-RPC接口訪问、操作数据库,基于此可实现与其它系统的交互与集成。
本文是使用Java通过XMLRPC接口操作Odoo数据库的简单演示样例。本例引用的jar包包含xmlrpc-common-3.1.3.jar, xmlrpc-client-3.1.3.jar和ws-commons-util-1.0.2.jar。如须要,可点击这里下载。

package memo.by.weichen;

import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;

/**
 * 
 * 通过XML-RPC接口訪问Odoo数据库
 * Test@Odoo 8.0
 * by WeiChen
 *
 */
public class OdooWSDemo {
	public static final String URL = "http://127.0.0.1:8069";
	public static final String DB = "demo";
	public static final int USERID = 1;
	public static final String PASS = "demo";
	
	public static void main(String[] args) throws Exception{
		XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
		XmlRpcClient client = new XmlRpcClient();
		config.setServerURL(new URL(String.format("%s/xmlrpc/2/object", URL)));
		client.setConfig(config);
		
		// 新建客户
		Integer id = (Integer) client.execute(
				"execute_kw", Arrays.asList(
						DB, USERID, PASS, "res.partner", "create",
						Arrays.asList(new HashMap() {
							{
								put("name", "苏州园区永旺梦乐城");
								put("customer", Boolean.TRUE);
							}
						})));
		// 更新客户
		client.execute("execute_kw", Arrays.asList(
				DB, USERID, PASS,
			    "res.partner", "write",
			    Arrays.asList(
			    	Arrays.asList(id),
			        new HashMap() {{ put("name", "永旺梦乐城苏州园区店"); }}
			    )
			));
		// 查找客户
		List<Object> partners = Arrays.asList((Object[])client.execute("execute_kw", Arrays.asList(
				DB, USERID, PASS,
			    "res.partner", "name_get",
			    Arrays.asList(Arrays.asList(id))
			)));
		if(partners!=null&&partners.size()>0){// partners格式: [[id, name]]
			Object[] partner = (Object[])partners.get(0);
			if(partner.length==2)
			System.out.println("客户名: "+partner[1]);
		}
		// 删除客户
		client.execute("execute_kw", Arrays.asList(
				DB, USERID, PASS,
			    "res.partner", "unlink",
			    Arrays.asList(Arrays.asList(id))));
		
		// 客户列表
		List<Object> customers = Arrays.asList((Object[]) client.execute(
				"execute_kw", Arrays.asList(
						DB, USERID, PASS, "res.partner", "search_read",
						Arrays.asList(Arrays.asList(
								// 设置查询条件
								// Arrays.asList("is_company", "=", true),
								Arrays.asList("customer", "=", true))),
						new HashMap() {
							{// 查询name字段, 限定最多返回100条记录
								put("fields", Arrays.asList("name"));
								put("limit", 100);
							}
						})));
		
		System.out.println("**********客户列表**********");
		for (int i=0;i<customers.size();i++){
			Map customer = (Map)customers.get(i);
			String name = (String)customer.get("name");
			System.out.println(name);
		}
		System.out.println("****************************");
	}
}
參考资料:

[1] https://www.odoo.com/documentation/8.0/api_integration.html

Odoo(OpenERP)开发实践:通过XML-RPC接口訪问Odoo数据库