需要下载ksoap2-android jar包
public class WebServices {
// webService地址
private String URL;
// 重设URL地址
public void setURL(String uRL) {
URL = uRL;
}
// 命名空间
private String namespace = "http://tempuri.org/";// 默认空间名
// 头信息
private String soupaction;
// 请求对象
private SoapObject request;
public SoapObject getRequest() {
return request;
}
/**
* 带参数的构造方法
*
* @param namespace
* 空间名称
* @param method_name
* 方法名称
* @param URL
* 通讯地址
*/
public WebServices(String method_name, String url) {
this.URL = url;
soupaction = namespace + method_name;
// 创建请求对象
request = new SoapObject(namespace, method_name);
}
/**
* 重设空间名称
*
* @param namespace
*/
public void setNamespace(String namespace) {
this.namespace = namespace;
}
/**
* 获取数据
*/
public Object getMeData() {
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER10);
envelope.bodyOut = request;
envelope.dotNet = true;
envelope.setOutputSoapObject(request);// 设置请求
// 建立网络连接
HttpTransportSE transport = new HttpTransportSE(URL, 50000);//设置一个50秒的超时
transport.debug = true;
// 定义返回结果
Object detail = null;
try {
transport.call(soupaction, envelope);
// 得到返回的结果
detail = (Object) envelope.getResponse();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
return detail;
}
public static String start(String url,String mathod,String jsonString){
WebServices services = new WebServices(mathod, url);
//json转json对象
JSONObject jsonobj;
try {
jsonobj = new JSONObject(jsonString);
Iterator it = jsonobj.keys();
while(it.hasNext()){//遍历JSONObject
String key = (String) it.next().toString();
services.getRequest().addPropertyIfValue(key,jsonobj.get(key));
}
Object result = services.getMeData();
if(result != null){
return result.toString();
}else{
return null;
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//获取返回结果
return "{result:'9999',error:'连接失败'}";
}
public static String startOnePar(String url,String method,String parValue,String parName){
try {
WebServices services = new WebServices(method, url);
if(parValue != null && !parValue.equalsIgnoreCase("")){
services.getRequest().addPropertyIfValue(parName,parValue);
if(method != null){
Object result = services.getMeData();
if(result != null){
return result.toString();
}else{
return null;
}
}
}
} catch (Exception e) {
e.printStackTrace();
return "{result:'9999',error:'链接异常'}";
}
return "{result:'9999',error:'连接失败'}";
}
}