日期:2014-05-16 浏览次数:20600 次
????? 想实现一个功能即让android访问远程数据库,但是网上很多人都不建议直连。据说问题多多。那么中间就加个第三者吧。
? ?? 实现思路:在数据库和android客户端添加一个webservice,处理每次客户端发来的请求。而在android客户端使用ksoap2解析webservice返回的数据。
??? 一 webservice 端,我使用序列化的方式实现的。不知道这里跟xml的实现哪个对手机来说更好。这里先放下,以后研究。
?????? 1.我使用的是xfire。新建一个webservice项目,然后我们开始写代码
??????? 2.一个接口
public interface ICompany {
public List<Company> getCompanyList();
}
???? 3一个实现类
public class ICompanyImp implements ICompany {
CompanyDAO comdao=new CompanyDAO();
//得到所有公司列表
public List<Company> getCompanyList() {
List<Company> list=new ArrayList<Company>();
try {
list=comdao.getCompanyList();
} catch (SQLException e) {
e.printStackTrace();
list=null;
}
return list;
}
}
? 注意:?我这里的返回值是list,不少webservice的基本类型,所以需要为它配置文件? 接口+.aegis.xml
4 接口+.aegis.xml
<?xml version="1.0" encoding="UTF-8"?>
<mappings>
<mapping>
<!--
<method name="getCollectionsRowCount">
<parameter index="0" componentType="java.lang.String"/>
</method>
-->
<!-- 返回的类型是Map的话,做法和List一样。但定义的类型,是Map中的Value部分 -->
<method name="getCompanyList">
<return-type componentType="bean.Company"/>
</method>
</mapping>
</mappings>
?
5.service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans >
<service xmlns="http://xfire.codehaus.org/config/1.0"
xmlns:s="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<name>MyService</name>
<serviceClass>main.service.ICompany</serviceClass>
<implementationClass>main.service.ICompanyImp</implementationClass>
<style mce_bogus="1">wrapped</style>
<use>literal</use>
<scope>application</scope>
<namespace>http://android.googlepages.com/</namespace>
</service>
</beans>
?
发布项目后,运行效果如图:
?
?
?
项目结构:

?
二 android客户端
?
?因为ksoap2解析webservice得到的数据类似于以下:getCompanyListResponse{out=anyType{Company=anyType{company=安徽江淮汽车股份有限公司; id=1; }; }; }
? 1 解析类:MyWebServiceHelper
public class MyWebServiceHelper {
// WSDL文档中的命名空间
private static final String targetNameSpace = "http://android.googlepages.com/";
// WSDL文档中的URL
private static final String WSDL = "http://192.168.1.144:8080/oilservice/services/MyService";
// 需要调用的方法名(获得Myervices中的helloWorld方法)
//需要调用的方法名(获得Myervices中的login方法)
private static final String getCompany="getCompanyList";
public List<Company> getCompanyList( ) {
List<Company> list=new ArrayList<Company>();
SoapObject request =new SoapObject(targetNameSpace,getCompany);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = false;
envelope.setOutputSoapObject(request);
AndroidHttpTransport httpTranstation = new AndroidHttpTransport (WSDL);
try {
httpTranstation.call(targetNameSpace+getCompany, envelope);
SoapObject soapObject = (SoapObject) envelope.getResponse();