文章目录
  1. 1. 简单介绍
  2. 2. 实例

简单介绍

在Java中使用ksoap2调用.NET的WCF接口挺方便,我们需要导入此方法的jar包实现该功能,可以向WCF服务提交数据获取返回信息。

实例

本例以简单的一个创建通知的WCF接口为例讲述Java与WCF的交互。
首先使用WcfTestClient测试下WCF接口的CreateNotice方法


测试传title和content两个字段值后返回IsSuccess和Message值。
下面新建一个Java项目导入ksoap2 jar包。
以下为我导入的jar包

新建一个接口ISoapService类, 用于专门读取WCF返回的SoapObject对象

1
2
3
4
5
6
7
package com.carlos.wcf;

import org.ksoap2.serialization.SoapObject;

public interface ISoapService {
SoapObject LoadResult();
}

调用WCF接口的类WcfService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package com.carlos.wcf;

import java.io.IOException;
import java.util.Map;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

public class WcfService implements ISoapService{

private static final String NAMESPACE="";//引号内改为自己接口的命名空间
private static final String URL="";//引号内改为自己接口的网址
private static final String SOAP_ACTION="";引号内改为自己接口的SOAP_ACTION
private static final String METHODNAME="CreateNotice";//引号内改为自己接口的方法名

private Map<String, String> map;

public WcfService(Map<String, String> map) {
this.map=map;
}

@Override
public SoapObject LoadResult() {
SoapObject object=new SoapObject(NAMESPACE, METHODNAME);
for(Map.Entry<String, String> entry:map.entrySet()){
System.out.println("key= "+entry.getKey()+" and value= "+entry.getValue());
object.addProperty(entry.getKey(), entry.getValue());
}

SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.bodyOut=object;
envelope.dotNet=true;
envelope.setOutputSoapObject(object);

HttpTransportSE transportSE=new HttpTransportSE(URL);
transportSE.debug=true;

try {
transportSE.call(SOAP_ACTION, envelope);
} catch (IOException e) {
System.out.println("IOException");
e.printStackTrace();
} catch (XmlPullParserException e) {
System.out.println("XmlPullParserException");
e.printStackTrace();
}

SoapObject result=(SoapObject) envelope.bodyIn;
return result;
}

}

WcfTest主类,获取返回结果并解析打印输出到控制台

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.carlos.wcf;

import java.util.HashMap;
import java.util.Map;

import org.ksoap2.serialization.SoapObject;

public class WcfTest {

public static void main(String[] args) {
Map<String, String> map=new HashMap<String, String>();
map.put("title", "提醒");
map.put("content", "晚上写篇博客");
WcfService wcf=new WcfService(map);
SoapObject result=(SoapObject) wcf.LoadResult().getProperty("result");
System.out.println(result);//返回的结果
int length=result.getPropertyCount();
System.out.println(result.getPropertyCount());
for(int i=0;i<length;i++){
System.out.println(result.getProperty(i));
}

}
}

控制台打印出的信息

文章目录
  1. 1. 简单介绍
  2. 2. 实例