注意:要先下载ksoap2.jar
关键代码:
private String namespace="";
private String methodName="getMobileCodeInfo"; private String url="";private String getPhoneNamberAddress(String phoneNamber)
{ //SoapObject实例 SoapObject soap=new SoapObject(namespace, methodName); soap.addProperty("mobileCode", phoneNamber);//设置请求参数 ,参数必须和API接口中保持一致 soap.addProperty("userID", "");//免费客户 //SoapSerializationEnvelope实例 SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet=true; envelope.setOutputSoapObject(soap);//发送请求 等价于envelop.bodyOut=soap; //AndroidHttpTransport实例 AndroidHttpTransport ht=new AndroidHttpTransport(url); ht.debug =true;获取结果:
//SoapPrimitive result=null; SoapObject result =null; try { ht.call(namespace+methodName,envelope); result = (SoapObject) envelope.bodyIn; //方法1 // 获取返回的结果 //result = ( SoapPrimitive)envelope.getResponse();//方法2 //result.toString(); } catch (Exception e) { e.printStackTrace(); } return result.getProperty("getMobileCodeInfoResult").toString(); }
一个工具类:
public class WSUtils { /** * * @description:调用webservice接口 * @param nameSpace 方法名空间 * @param methodName 方法名 * @param params 请求参数 * @param wsdl url地址 * @return SoapObject对象 * @throws Exception */ public static SoapObject callWS(String nameSpace, String methodName, Map params, String wsdl) throws Exception { final String SOAP_ACTION = nameSpace + methodName; SoapObject soapResult = null; //SoapObject实例 SoapObject mSoapObject = new SoapObject(nameSpace, methodName); if (params != null && !params.isEmpty()) { for (Iterator it = params.entrySet().iterator(); it.hasNext();) { // 遍历MAP Map.Entry<String, Object> e = (Map.Entry<String, Object>) it.next(); mSoapObject.addProperty(e.getKey().toString(), e.getValue());//设置请求参数 } } //SoapSerializationEnvelope实例 SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);// SOAP envelope.dotNet = true; envelope.bodyOut = mSoapObject;//发送请求 //HttpTransportSE实例 HttpTransportSE ht = new HttpTransportSE(wsdl,10*1000); ht.debug =true; //获取结果 ht.call(SOAP_ACTION, envelope); soapResult = (SoapObject) envelope.bodyIn; return soapResult; }}