封装好的用于请求webservice服务器的soap工具类

首先先下载ksoap2包

然后:

package jiuzhi.jiuzhiyingcai.http;

import android.os.Handler;
import android.os.Message;
import android.support.v4.util.SimpleArrayMap;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.kxml2.kdom.Element;
import org.kxml2.kdom.Node;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import jiuzhi.jiuzhiyingcai.config.ConfigValue;
import jiuzhi.jiuzhiyingcai.utils.*;

/**
 * Created by GQD on 2017/5/31.
 */

public class WebServiceUtils {
    // 访问的服务器是否由dotNet开发
    public static boolean isDotNet = false;
    // 线程池的大小
    private static int threadSize = 5;
    // 创建一个可重用固定线程数的线程池,以共享的无界队列方式来运行这些线程
    private static ExecutorService threadPool = Executors.newFixedThreadPool(threadSize);
    // 连接响应标示
    public static final int SUCCESS_FLAG = 0;
    public static final int ERROR_FLAG = 1;
    //AppSecret
    static String AppSecret = ConfigValue.AppSecret;
    //时间戳
    static long currentTimeInLong = TimeUtils.getCurrentTimeInLong();
    static int time= Math.round(currentTimeInLong / 1000);
    static String CurTime = String.valueOf(time);
    //随机数
    static Random random=new Random();
    static int nonce  = random.nextInt();
    static String Nonce = String.valueOf(nonce);
    static String shaString=AppSecret+Nonce+CurTime;
    static String CheckSum = new Sha1().getDigestOfString(shaString).toLowerCase();
    /**
     * 调用WebService接口,此方法只访问过用Java写的服务器
     *
     * @param endPoint        WebService服务器地址
     * @param nameSpace       命名空间
     * @param methodName      WebService的调用方法名
     * @param mapParams       WebService的参数集合,可以为null`1 qw
     * @param reponseCallBack 服务器响应接口
     */
    public static void call(final String endPoint,
                            final String nameSpace,
                            final String methodName,
                            SimpleArrayMap<String, String> mapParams,
                            final Response reponseCallBack) {
        // 1.创建HttpTransportSE对象,传递WebService服务器地址
        final HttpTransportSE transport = new HttpTransportSE(endPoint);
        transport.debug = true;
        // 2.创建SoapObject对象用于传递请求参数
        final SoapObject request = new SoapObject(nameSpace, methodName);
        // 2.1.添加参数也可以不传
        if (mapParams != null) {
            for (int index = 0; index < mapParams.size(); index++) {
                String key = mapParams.keyAt(index);
                String value = mapParams.get(key);
                request.addProperty(key, value);
            }
        }
        //添加header
        Element[] header=new Element[1];
        header[0]=new Element().createElement("","ss");
        Element appKey = new Element().createElement("", "ss");
        appKey.addChild(Node.TEXT, ConfigValue.AppKey);
        header[0].addChild(Node.ELEMENT, appKey);

        Element appTime = new Element().createElement("", "ss");
        appTime.addChild(Node.TEXT, CurTime);
        header[0].addChild(Node.ELEMENT, appTime);

        Element sum = new Element().createElement("", "ss");
        sum.addChild(Node.TEXT,Nonce);
        header[0].addChild(Node.ELEMENT, sum);

        Element check = new Element().createElement("", "");
        check.addChild(Node.TEXT,CheckSum);
        header[0].addChild(Node.ELEMENT, check);

        // 3.实例化SoapSerializationEnvelope,传入WebService的SOAP协议的版本号
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.headerOut = header;
        envelope.bodyOut = request;
        envelope.dotNet = isDotNet; // 设置是否调用的是.Net开发的WebService
        envelope.setOutputSoapObject(request);

        // 4.用于子线程与主线程通信的Handler,网络请求成功时会在子线程发送一个消息,然后在主线程上接收
        final Handler responseHandler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                // 根据消息的arg1值判断调用哪个接口
                if (msg.arg1 == SUCCESS_FLAG)
                    reponseCallBack.onSuccess((SoapObject) msg.obj);
                else
                    reponseCallBack.onError((Exception) msg.obj);
            }

        };

        // 5.提交一个子线程到线程池并在此线种内调用WebService
        if (threadPool == null || threadPool.isShutdown())
            threadPool = Executors.newFixedThreadPool(threadSize);
        threadPool.submit(new Runnable() {

            @Override
            public void run() {
                SoapObject result = null;
                try {
                    // 解决EOFException
                    System.setProperty("http.keepAlive", "false");
                    // 连接服务器
                    transport.call(null, envelope);
                    if (envelope.getResponse() != null) {
                        // 获取服务器响应返回的SoapObject
                        result = (SoapObject) envelope.bodyIn;
                    }
                } catch (IOException e) {
                    // 当call方法的第一个参数为null时会有一定的概念抛IO异常
                    // 因此需要需要捕捉此异常后用命名空间加方法名作为参数重新连接
                    e.printStackTrace();
                    try {
                        transport.call(nameSpace + methodName, envelope);
                        if (envelope.getResponse() != null) {
                            // 获取服务器响应返回的SoapObject
                            result = (SoapObject) envelope.bodyIn;
                        }
                    } catch (Exception e1) {
                        // e1.printStackTrace();
                        responseHandler.sendMessage(responseHandler.obtainMessage(0, ERROR_FLAG, 0, e1));
                    }
                } catch (XmlPullParserException e) {
                    // e.printStackTrace();
                    responseHandler.sendMessage(responseHandler.obtainMessage(0, ERROR_FLAG, 0, e));
                } finally {
                    // 将获取的消息利用Handler发送到主线程
                    responseHandler.sendMessage(responseHandler.obtainMessage(0, SUCCESS_FLAG, 0, result));
                }
            }
        });
    }

    /**
     * 设置线程池的大小
     *
     * @param threadSize
     */
    public static void setThreadSize(int threadSize) {
        WebServiceUtils.threadSize = threadSize;
        threadPool.shutdownNow();
        threadPool = Executors.newFixedThreadPool(WebServiceUtils.threadSize);
    }

    /**
     * 服务器响应接口,在响应后需要回调此接口
     */
    public interface Response {
        public void onSuccess(SoapObject result);

        public void onError(Exception e);
    }

}

转载于:https://my.oschina.net/u/3456384/blog/967435

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用 SOAPWebService 示例: 1. 定义 WebService 接口:首先,你需要定义一个包含要提供的方法的接口。例如,你可以创建一个名为 "CalculatorService" 的接口,其中包含加法、减法等数学运算的方法声明。 2. 实现 WebService 接口:接下来,你需要实现这个接口。创建一个名为 "CalculatorServiceImpl" 的类,并实现 CalculatorService 接口中的方法。在方法中编写具体的数学运算逻辑。 3. 创建 WebService 服务:在你的项目中创建一个 WebService 服务类,例如 "CalculatorWebService"。在这个类上添加 `@WebService` 注解,并指定 `endpointInterface` 为你创建的接口名称,例如 `CalculatorService`。 4. 配置 WebService:在项目的配置文件中,为你的 WebService 添加必要的配置信息。这可能包括指定 WebService 的名称、命名空间、端口等。 5. 发布 WebService:通过部署你的项目,将 WebService 发布到一个 Web 服务器上。这样其他应用程序就可以通过 SOAP 协议访问你的 WebService。 6. 使用 WebService:其他应用程序可以通过创建一个 SOAP 客户端来使用你的 WebService。根据你所使用的编程语言和框架,可以生成客户端代码或手动编写代码来调用 WebService 提供的方法。 以上是一个基本的使用 SOAPWebService 示例。具体实现和配置可能因编程语言和框架而异,你可以根据自己的需求和技术栈进行相应的调整和扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值