Android使用ksoap2连接webserver(JAX-WS)访问数据库
首先下载jar包:ksoap2-android-assembly-2.4-jar-with-dependencies.jar
为了重复使用访问webservice的方法,把该方法写成一个工具类。
其中NetworkState.isConnected方法用于检查网络是否连接。
调用方法:String s = RequestWebService.request("webservice方法名",参数字符串数组);s即为webservice返回结果,我用的是json格式字符串,然后再利用阿里巴巴的fastjson库解析。
特别注意:本人是用jax-ws开发的webservice,传参数的时候,参数名必须为arg0,arg1,arg2...,否则会找不到参数。
public final class RequestWebService { @SuppressWarnings("finally") public static String request(String methodName,String[] args){ String s = ""; ConnectivityManager connectivityManager = NetworkState.init(MyApplication.getInstance().getApplicationContext()); Boolean isConnected = NetworkState.isConnected(connectivityManager); if(isConnected){ try { Properties prop = new Properties(); InputStream in = RequestWebService.class.getResourceAsStream("/setting.properties"); prop.load(in); String http = prop.getProperty("http").trim(); String ip = prop.getProperty("ip").trim(); String port = prop.getProperty("port").trim(); String webservice = prop.getProperty("webservice").trim(); //Toast.makeText(MainActivity.this, ip, Toast.LENGTH_SHORT).show(); String serviceUrl = http+"://"+ip+":"+port+"/"+webservice+"/AlarmPort"; String namespace = http+"://server/"; //String methodName = "login"; // 第1步:创建SoapObject对象,并指定WebService的命名空间和调用的方法名 SoapObject request = new SoapObject(namespace, methodName); // 第2步:设置WebService方法的参数 for(int i=0;i<args.length;i++){ request.addProperty("arg"+i, args[i]); } // 第3步:创建SoapSerializationEnvelope对象,并指定WebService的版本 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // 设置bodyOut属性 envelope.dotNet = false; envelope.setOutputSoapObject(request); // 第4步:创建HttpTransportSE对象,并指定WSDL文档的URL HttpTransportSE ht = new HttpTransportSE(serviceUrl); // 第5步:调用WebService ht.call(namespace+methodName, envelope); SoapObject result = (SoapObject)envelope.bodyIn; s = (String)result.getProperty(0).toString(); }catch (Exception e){ e.printStackTrace(); s = "{success:false,error:'【"+e.getMessage()+"】'}"; } finally{ return s; } }else{ return "{success:false,error:'网络未连接,请检查网络!'}"; } } }
相关推荐
Nostalgiachild 2020-11-13
韩伟佳 2020-10-09
wuleihenbang 2020-09-16
zzqLivecn 2020-07-09
chenjinlong 2020-06-10
yinbaoshiguang 2020-06-09
sgafdsg 2020-06-04
ustcrding 2020-06-03
chenjinlong 2020-06-03
AndroidGA 2020-06-01
安辉 2020-05-27
绿豆饼 2020-05-26
CNETNews 2020-05-26
xilove0 2020-05-12
绿豆饼 2020-05-12
ChainDestiny 2020-05-07
doomvsjing 2020-05-07
hqulyc 2020-05-05
lyccsu 2020-04-30