安卓SoapObjectc soap调用webservicee怎么传送参

由于项目中要使用Android调用C#写的WebService,于是便有了这篇文章。在学习的过程中,发现在C#中直接调用WebService方便得多,直接添加一个引用,便可以直接使用将WebService当做一个对象使用,利用Vs2010中的代码提示功能就能爽歪歪地把想要的东西全部点出来。在Android调用,麻烦了一点,但是也还好。主要是我们需要自己在代码中确定要调用WebService的方法名是什么,要传给WebService什么参数以及对应的参数名,另外,一些额外的信息比如soap的版本号,也需要了解了。
1.准备工作:写一个测试用的WebService
首先,让我们先准备一下WebService,WebService的代码很简单,一个是返回HelloWorld字段,另一个是原样返回用户发给WebService的字符串。
using System.Collections.G
using System.L
using System.W
using System.Web.S
namespace testAndroidCall
/// &summary&
/// WebService1 的摘要说明
/// &/summary&
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ponentModel.ToolboxItem(false)]
// 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
// [System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
[WebMethod]
public string HelloWorld()
return "Hello World";
[WebMethod]
public string EchoMessage(string msg)
接着,我们需要下载一个Android中调用WebService的类库
比较常用的有Ksoap2,可以从进行下载。也可以。
将下载的ksoap2-android-assembly-2.4-jar-with-dependencies.jar包复制到Eclipse工程的lib目录中,当然也可以放在其他的目录里。同时在Eclipse工程中引用这个jar包。
2、完成简单的Android布局代码的编写
(1) 在AdroidManifest.xml中加入权限,&manifest&节点里面加入下面这句话
&!-- 访问网络的权限 --&
&uses-permission android:name="android.permission.INTERNET" /&
(2)、我们在Android中建立两个按钮,分别对应WebService中的两个方法
private void initBtn() {
View btnHelloWorld = this.findViewById(R.id.btnHelloWorld);
btnHelloWorld.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Map&String, String& values = new HashMap&String, String&();
values.put("msg", "这是Android手机发出的信息");
Request(METHOD_HELLO_WORLD);
View btnEchoMessage = this.findViewById(R.id.btnEchoMessage);
btnEchoMessage.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Map&String, String& values = new HashMap&String, String&();
values.put("msg", "这是Android手机发出的信息");
Request(METHOD_ECHO_MESSAGE,values);
在Request(&)方法中,我们主要是想实现将WebService中方法名和调用的参数传入WebService。在这个方法中,主要应用了AsyncTask来处理WebService的调用,因为调用WebService是网络操作,可能会比较耗时,在Android3.0以上,已经不允许在UI线程直接进行网络操作,另外,AsyncTask还可以直接更新UI上的控件。
* 执行异步任务
* @param params
方法名+参数列表(哈希表形式)
public void Request(Object... params) {
new AsyncTask&Object, Object, String&() {
protected String doInBackground(Object... params) {
if (params != null && params.length == 2) {
return CallWebService((String) params[0],
(Map&String, String&) params[1]);
} else if (params != null && params.length == 1) {
return CallWebService((String) params[0], null);
return null;
protected void onPostExecute(String result) {
if (result != null) {
tvMessage.setText("服务器回复的信息 : " + result);
}.execute(params);
3、分析Android调用WebService的代码
我们的重点将放在CallWebService()这个方法中。这个方法里面封装了ksoap2类库里面调用WebService的一些对象。
(1) 指定webservice的命名空间和调用的方法名,如:
SoapObject request =new SoapObject(Namespace,MethodName);
SoapObject类的第一个参数表示WebService的命名空间,可以从WSDL文档中找到WebService的命名空间。第二个参数表示要调用的WebService方法名。
(2) 设置调用方法的参数值,如果没有参数,可以省略,设置方法的参数值的代码如下:
Request.addProperty(&param1&,&value&);
Request.addProperty(&param2&,&value&);
要注意的是,addProperty方法的第1个参数表示调用方法的参数名,该参数值要与服务端的WebService类中的方法参数名一致,并且参数的顺序一致。
(3) 生成调用Webservice方法的SOAP请求信息。该信息由SoapSerializationEnvelope对象描述,代码为:
SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER12);
Envelope.bodyOut =
创建SoapSerializationEnvelope对象时需要通过SoapSerializationEnvelope类的构造方法设置SOAP协议的版本号。该版本号需要根据服务端WebService的版本号设置。在创建SoapSerializationEnvelope对象后,不要忘了设置SOAPSoapSerializationEnvelope类的bodyOut属性,该属性的值就是在第一步创建的SoapObject对象。
SOAP协议的版本号可以从WebService的WSDL文档(在本例中是&&)
(4) 创建HttpTransportsSE对象。通过HttpTransportsSE类的构造方法可以指定WebService的WSDL文档的URL:
HttpTransportSE ht=new HttpTransportSE(WEB_SERVICE_URL);
WEB_SERVICE_URL是指WebService的地址,如"http://192.168.0.121:80/testAndroidCall/WebService1.asmx?wsdl"这样的
(5)使用call方法调用WebService方法,代码:
ht.call(null,envelope);
Call方法的第一个参数一般为null,第2个参数就是在第3步创建的SoapSerializationEnvelope对象。
(6)使用getResponse方法获得WebService方法的返回结果,代码:
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
(7)最后,附上完整的CallWebService()方法
* 调用WebService
* @return WebService的返回值
public String CallWebService(String MethodName, Map&String, String& Params) {
// 1、指定webservice的命名空间和调用的方法名
SoapObject request = new SoapObject(Namespace, MethodName);
// 2、设置调用方法的参数值,如果没有参数,可以省略,
if (Params != null) {
Iterator iter = Params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
request.addProperty((String) entry.getKey(),
(String) entry.getValue());
// 3、生成调用Webservice方法的SOAP请求信息。该信息由SoapSerializationEnvelope对象描述
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER12);
envelope.bodyOut =
// c#写的应用程序必须加上这句
envelope.dotNet = true;
HttpTransportSE ht = new HttpTransportSE(WEB_SERVICE_URL);
// 使用call方法调用WebService方法
ht.call(null, envelope);
} catch (HttpResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
final SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
if (result != null) {
Log.d("----收到的回复----", result.toString());
return result.toString();
} catch (SoapFault e) {
Log.e("----发生错误---", e.getMessage());
e.printStackTrace();
return null;
4、运行代码
要运行文章中的代码,请先将WebService部署在IIS上,要保证Android手机的测试程序和WebService处在同一个局域网中。
阅读(...) 评论()webservice
android 设置head头发送 获取 -
- ITeye技术网站
android 发送方法
//里面地址对应上面图片的namespace
SoapObject request = new SoapObject("/", "hello");
//这个是配置参数
request.addProperty("name","dddddddddddd");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
Element[] header = new Element[1];
header[0] = new Element().createElement("/","hello");
header[0].setAttribute("/","token","xiebuqing");
envelope.headerOut=
envelope.bodyOut =
envelope.setOutputSoapObject(request);
// 设置是否调用的是dotNet开发的WebService
envelope.dotNet =
//对应图片上的soap:address
HttpTransportSE androidHttpTransport = new HttpTransportSE("http://127.0.0.1:8080/wzkj/webservice/helloworld");
//call的第一个参数对应图片上的soapAction=""
androidHttpTransport.call("", envelope);
SoapObject result = (SoapObject)envelope.bodyIn;
//这里我获取第一个数据
System.out.println(result.getProperty(0).toString());
} catch (Exception e) {
e.printStackTrace();
通过抓包工工具获取到格式
&v:Envelope xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:d=\"http://www.w3.org/2001/XMLSchema\" xmlns:c=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:v=\"http://schemas.xmlsoap.org/soap/envelope/\"&
&v:Header&
&n0:hello n0:token=\"xiebuqing\" xmlns:n0=\"/\" /&
&/v:Header&
&n1:hello id=\"o0\" c:root=\"1\" xmlns:n1=\"/\"&
&name i:type=\"d:string\"&
dddddddddddd
&/n1:hello&
&/v:Envelope&
web 端口发送的格式
&soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"&
&soap:Header&
&tns:RequestSOAPHeader xmlns:tns=\"http://192.168.1.113:8080/wzkj/webservice/helloworld\"&
&tns:spId&
&/tns:spId&
&tns:spPassword&
&/tns:spPassword&
&/tns:RequestSOAPHeader&
&/soap:Header&
&ns2:hello xmlns:ns2=\"/\"&
&/ns2:hello&
&/soap:Body&
&/soap:Envelope&
在head中两个格式不一样需要在获取的时候作解析
* @FileName
: SOAPAuthIntercepter
* @Copy Right : WZKJ Technology Ltd
* @Comments
: soap认证拦截器
:liyulong
* @Create Date:
* @Modified By:
* @Modified Date:
* @Why & What is modified
* @version
package com.wzkj.webservice.
import java.util.L
import javax.xml.soap.SOAPE
import javax.xml.soap.SOAPH
import javax.xml.soap.SOAPM
import org.apache.cxf.binding.soap.SoapH
import org.apache.cxf.binding.soap.SoapM
import org.apache.cxf.binding.soap.saaj.SAAJInI
import org.apache.cxf.headers.H
import org.apache.cxf.interceptor.F
import org.apache.cxf.phase.AbstractPhaseI
import org.apache.cxf.phase.P
import org.springframework.beans.factory.annotation.A
import org.w3c.dom.E
import com.wzkj.core.util.BlowfishU
import com.wzkj.web.entity.C
import com.wzkj.web.mapper.CipherTextM
public class SOAPAuthIntercepter
extends AbstractPhaseInterceptor&SoapMessage&{
private SAAJInInterceptor saa = new SAAJInInterceptor();
@Autowired
private CipherTextMapper cipherTextM
public SOAPAuthIntercepter(String phase) {
super(phase);
public SOAPAuthIntercepter(){
// 指定该拦截器在哪个阶段被激发
super(Phase.PRE_INVOKE);
* 处理消息
public void handleMessage(SoapMessage message) throws Fault {
SOAPMessage mess = message.getContent(SOAPMessage.class);
//判断消息是否为空
if (mess == null) {
saa.handleMessage(message);
mess = message.getContent(SOAPMessage.class);
SOAPHeader head =
head = mess.getSOAPHeader();
} catch (Exception e) {
e.printStackTrace();
if (head == null) {
throw new Fault(new SOAPException("SOAP消息头格式不对!"));
// 获取SOAP消息的全部头
List&Header& headers = message.getHeaders();
if (null == headers || headers.size() & 1) {
throw new Fault(new SOAPException("SOAP消息头格式不对!"));
//认证token令牌
if(!checkQnameHeader(headers)){
throw new Fault(new SOAPException("认证失败"));
* 认证token令牌
* @param headers 消息体
* @return boolean
private boolean checkQnameHeader(List&Header& headers) {
SoapHeader soapHeader = (SoapHeader) headers.get(0);
Element element = (Element) soapHeader.getObject();
String token = element.getAttribute("n0:token");
Ciphertext cipher = cipherTextMapper.getById(1);
BlowfishUtil chiper = new BlowfishUtil(cipher.getKey());
String value = chiper.decryptString(token);
return value.equals(cipher.getText());
public String getToken() {
public void setToken(String token) {
this.token =
umbrellall1
浏览: 52062 次
来自: 成都
很有用,感谢!!
感谢打发的
good 正是我想要的,如果楼主可以弄成开源的或者更加精致的话 ...
请教一下,这个效果拖动后,会出现一层黑色的膜,可以怎么去掉呢? ...
图片可以设为背景,但是大小不对啊
不能全屏显示呀 上传我的文档
 下载
 收藏
该文档贡献者很忙,什么也没留下。
 下载此文档
正在努力加载中...
Android调用webservice 并传递实体类
下载积分:500
内容提示:Android调用webservice 并传递实体类
文档格式:PDF|
浏览次数:83|
上传日期: 20:00:47|
文档星级:
该用户还上传了这些文档
Android调用webservice 并传递实体类
官方公共微信已解决:android 调用本地的webservice 引用不到 - 推酷
已解决:android 调用本地的webservice 引用不到
背景,需要自己用 java 写一个 webservice, 然后写一个 android的客户端去调用它。
我这里折腾了2天,最后终于调成功了。以图为证。
1,& MyEclipse开发webservice
&&&&& & & MyEclipse 建 webservice之前,先把 Tomcat 设置好: MyEclipse -& Preference -& MyEclipse -& Servers -& Tomcat -& Configure Tomcat 7.x -& 选Enable,输入Tomcat home directory,tomcat base directory 和 tomcat temp directory 会自己填好,保存
&&&& 核心的代码:
public String sayHello(String name)
return &hello,& +
&&&&& 因为用 Eclipse 写 webservice,需要引用到一些的包,可能因为一些未知的原因,老是不停的报错。折腾了一些时间后,果断放弃之。用MyEclipse 10 去写webservice, 一路next, 节省了不少时间。
&&&&& MyEclipse建webservice主要步聚:新建一个web项目,右击之,新建 -& MyEclipse -& WebService & Project: 你的项目名; Framework: JAX-WS; Strategy: buttom-up scenario -& Next --& Java Class 选 自己新建的HelloWorld, ------- 具体的操作参考 下面别人的2篇日志:
myeclipse10创建jax-ws方式的webservice(一).cn/s/blog_4d91c1660100xly3.html
&&&&&&&&& myeclipse10创建jax-ws方式的webservice(二) .cn/s/blog_4d91c1660100xlyt.html
&&&&& webservice弄好后,应该 可以通过URL访问;若别人的机器不能访问,则需要关闭 防火墙 或 给 8080端口开启一个例外:
2,android项目中引用 webservice, 一般用第三方的 ksoap
&&&&&&& 这里我用的是:ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar
&&&&&&& (ksoap 2.5.2 的下载地址:
&&&&&& 之前我用 ksoap3.0的包,可以调用到别人用.net写的 但就是调不到自己的service。现在换成低版本的,反而成功了。
3,& 关于引用 ksoap2的方式,与我们在java项目中通常的引用方式不一样。
&&&& 在 android项目中,将 ksoap 2.5.2的包放在 libs文件夹中,选中,右键& -& build path -& 选中android项目,右键 -& build path -& config build path -& 在 Order and Export选项卡页面中,选中 ksoap 2.5.2的包 -& 保存
4, 读取 webservice的方法
&&& 这个方法既要能够访问 .net的webservice, 又要访问 java的webservice.
&&& 贴一下我的 ReadRemoteService.java
package com.
import java.util.L
import org.ksoap2.SoapE
import org.ksoap2.SoapF
import org.ksoap2.serialization.SoapO
import org.ksoap2.serialization.SoapSerializationE
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.transport.AndroidHttpT
public class ReadRemoteService {
public String NAMESPACE;
public String METHODNAME;
public String WEBSERVICEURL;
public Boolean ISDOTNETSERVICE;
public List&String& LISTPARAMS;
public ReadRemoteService(String nameSpace,String methodName,String WebServiceUrl,Boolean IsDotNetService,List&String& lstParams)
this.NAMESPACE = nameS
this.METHODNAME = methodN
this.WEBSERVICEURL=WebServiceU
this.ISDOTNETSERVICE = IsDotNetS
this.LISTPARAMS=lstP
public Object Get()
return ReadService();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return &ERROR:& + e.getMessage();
private Object ReadService() throws Exception {
// 命名空间
String nameSpace = this.NAMESPACE;
// 调用的方法名称
String methodName = this.METHODNAME;
//&getMobileCodeInfo&;
// EndPoint
String endPoint = this.WEBSERVICEURL;
//&.cn/WebServices/MobileCodeWS.asmx&;
// SOAP Action
String soapAction = this.NAMESPACE + this.METHODNAME;
//&.cn/getMobileCodeInfo&;
// 指定WebService的命名空间和调用的方法名
SoapObject rpc = new SoapObject(nameSpace, methodName);
// 设置需调用WebService接口需要传入的两个参数mobileCode、userId
/*rpc.addProperty(&mobileCode&, phoneSec);
rpc.addProperty(&userId&, &&);*/
if(this.LISTPARAMS !=null)
if(this.LISTPARAMS.size() % 2 !=0 || this.LISTPARAMS.size()&2)
throw new Exception(&params should be even!&);
for(int i=0;i&this.LISTPARAMS.size()-1;i=i+2)
//System.out.println(this.LISTPARAMS.get(i));
rpc.addProperty(this.LISTPARAMS.get(i), this.LISTPARAMS.get(i+1));
//throw new Exception(&params:& + this.LISTPARAMS.get(i) + & & + this.LISTPARAMS.get(i+1));
// 生成调用WebService方法的SOAP请求信息,并指定SOAP的版本
SoapSerializationEnvelope envelope
= new SoapSerializationEnvelope(SoapEnvelope.VER11);
//(SoapEnvelope.VER10);
envelope.bodyOut =
// 设置是否调用的是dotNet开发的WebService
envelope.dotNet = this.ISDOTNETSERVICE;
envelope.encodingStyle=&UTF-8&;
if(!envelope.dotNet)
endPoint = endPoint + &?wsdl&;
// 等价于envelope.bodyOut =
envelope.setOutputSoapObject(rpc);
// 调用WebService
HttpTransportSE transport = new HttpTransportSE(endPoint);
//AndroidHttpTransport transport =new AndroidHttpTransport(endPoint);
//transport.debug=
/*transport.call(soapAction, envelope);*/
/* if(!envelope.dotNet)
transport.call(null, envelope);
transport.call(soapAction,envelope);
} catch (Exception e) {
e.printStackTrace();
return &ERROR:& + e.getMessage();
// 获取返回的数据
SoapObject object=
SoapFault error=
object = (SoapObject) envelope.bodyIn;
}catch(Exception e)
error = (SoapFault)envelope.bodyIn;
// detail =(SoapObject) envelope.getResponse();
System.out.println(&Error message : &+error.toString());
// 获取返回的结果
//String result = object.getProperty(0).toString();
// 将WebService返回的结果显示在TextView中
// lbl1.setText(result);
if(error!=null)
Common.java
package com.
import java.util.ArrayL
import android.widget.TextV
public class Common {
public static void SolveRemoteService(Object ServiceResult,TextView tvResult)
java.util.Date now=new java.util.Date();
if(ServiceResult instanceof String)
tvResult.setText(now.toLocaleString() + & & + &String:& + ServiceResult.toString());
}else if(ServiceResult instanceof ArrayList)
StringBuilder sb=new StringBuilder();
Object[] values = ((ArrayList) ServiceResult).toArray(); //正确
for(Object x:values)
sb.append(x.toString() + &\r\n&);
tvResult.setText(now.toLocaleString() + & & + &ArrayList:& +sb.toString());
tvResult.setText(now.toLocaleString() + & & + &Other types:& + ServiceResult.toString());
5, 在android项目中调用 刚才的方法的样例
&&&& 1)访问 .net的webservice 样例
String sNameSpace=&.cn/&;
String sMethodName=&getMobileCodeInfo&;
String sWebserviceUrl=&.cn/WebServices/MobileCodeWS.asmx&;
Boolean IsDotNetService=
List&String& lstParams=new ArrayList&String&();
lstParams.add(&mobileCode&);
lstParams.add(sPhone);
lstParams.add(&userId&);
lstParams.add(&&);
ReadRemoteService readService=
new ReadRemoteService(sNameSpace,sMethodName,sWebserviceUrl,IsDotNetService,lstParams);
Object Result = readService.Get();
Common.SolveRemoteService(Result,tv_Result);
&& 2)& 访问 java的webService
&&&&&&&&& 注意:前面我在webservice中的参考名是 name, 这里却写的是 arg0, 为什么呢?因为 用MyEclipse在自动帮我生成webservice 相关的代码时,参数名已被改为 arg0.
&&&&&&&&& 如果 坚持写 name, 结果只有一个,返回的是:hello,null.
tv_WsResult.setText(&&);
String sName = et_Name.getText().toString().trim();
String sWsUrl=et_WsUrl.getText().toString().trim(); //sWsUrl应该是 http://localhost:8080/testWebService/HelloWorldPort
String sResult = ReadMyService(sName,sWsUrl);
java.util.Date now=new java.util.Date();
tv_WsResult.setText(now.toLocaleString() + & & + sResult);*/
String sNameSpace=&/&;
String sMethodName=&sayHello&;
String sWebserviceUrl=sWsU
Boolean IsDotNetService=
List&String& lstParams=new ArrayList&String&();
lstParams.add(&arg0&);
lstParams.add(sName);
java.util.Date now=new java.util.Date();
tv_WsResult.setText(now.toLocaleString() + & & + sName); */
ReadRemoteService readService=
new ReadRemoteService(sNameSpace,sMethodName,sWebserviceUrl,IsDotNetService,lstParams);
Object Result = readService.Get();
Common.SolveRemoteService(Result,tv_WsResult);
6, 特别注意:在第5步,传参时,命名空间,方法名,WebServiceUrl都不能错。
&&& 而且java是大小写敏感的,请确保你的webservice在浏览器中首先能访问。
&&& 在模拟器上调 本机的webservice,用 本机的IP地址,不用 localhost.
至此,全文 结束。感谢大家。
已发表评论数()
已收藏到推刊!
请填写推刊名
描述不能大于100个字符!
权限设置: 公开
仅自己可见
正文不准确
排版有问题
没有分页内容
视频无法显示
图片无法显示

我要回帖

更多关于 c soap webservice 的文章

 

随机推荐