Android Webservice网络请求工具

前言
对于Webservicer的请求方式,可以利用HttpUrlconnection请求,在此我利用封装好的KSOAP2进行网络请求封装,Ksoap2不不懂得自己百度,我这个人比较直接,代码的逻辑基本都有注释。


1.主要工具类[KSoapUtils ]:

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.ice.android.File.FileUtils;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;
import java.io.File;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.Map;

/**
 * Created by Relin
 * WebService工具类
 * on 2017/3/14.
 */

public class KSoapUtils {

    //请求成功标识
    public final int WHAT_KSOAP_ON_FAILURE = 0x011;
    //请求失败标识
    public final int WHAT_KSOAP_ON_SUCCEED = 0x022;
    //服务器地址
    private String url;
    //服务器域名
    private String nameSpace;
    //请求监听
    private OnKSoapListener onKSoapListener;
    //Soap的版本号[SoapEnvelope.VER10]1.0版本的默认版本
    private int soapVersion = SoapEnvelope.VER10;


    /**
     * 获取KSoapUtils的实例对象
     *
     * @param url
     * @param nameSpace
     * @return
     */
    public KSoapUtils(String url, String nameSpace, int soapVersion) {
        this.url = url;
        this.nameSpace = nameSpace;
        this.soapVersion = soapVersion;
    }


    /**
     * 执行网络请求
     *
     * @param methodName
     * @param parameter
     */
    public void execute(final String methodName, final KSoapParameter parameter, final OnKSoapListener onKSoapListener) {
        this.onKSoapListener = onKSoapListener;
        new Thread() {
            @Override
            public void run() {
                super.run();
                HttpTransportSE httpTransportSE = new HttpTransportSE(url, 30 * 1000);//30秒延迟
                httpTransportSE.debug = true;
                //使用SOAP1.1协议创建Envelop对象
                SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(soapVersion);
                SoapObject soapObject = new SoapObject(nameSpace, methodName);
                //添加请求的参数
                if (parameter != null) {
                    //添加字符串类型的参数
                    if (parameter.getStringParameter() != null) {
                        Map<String, String> stringParameter = parameter.getStringParameter();
                        for (String key : stringParameter.keySet()) {
                            soapObject.addProperty(key, stringParameter.get(key));
                        }
                    }
                    //添加文件类型的参数
                    if (parameter.getFileParameter() != null) {
                        Map<String, File> fileParameter = parameter.getFileParameter();
                        for (String key : fileParameter.keySet()) {
                            soapObject.addProperty(key, FileUtils.getInstance().fileToString(fileParameter.get(key)));
                        }
                    }
                }
                envelope.bodyOut = soapObject;
                /// 设置与.NET提供的webservice保持较好的兼容性
                envelope.dotNet = true;
                //吊起请求
                try {
                    httpTransportSE.call(nameSpace + "/" + methodName, envelope);
                    if (envelope.getResponse() != null) {
                        SoapObject result = (SoapObject) envelope.bodyIn;
                        String stringResult = URLDecoder.decode(result.getProperty(0).toString(), "UTF-8");
                        //传递给Handler
                        Message msg = kSoapHandler.obtainMessage();
                        msg.obj = stringResult;
                        msg.what = WHAT_KSOAP_ON_SUCCEED;
                        kSoapHandler.sendMessage(msg);
                        Log.i(this.getClass().getSimpleName(), "result :" + stringResult);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    String msg;
                    if (e instanceof SocketTimeoutException) {
                        msg = "连接服务器超时,请检查网络。";
                    } else if (e instanceof UnknownHostException) {
                        msg = "未知服务器,请检查配置。";
                    } else if (e.getMessage().contains("status: 500")) {
                        msg = e.getMessage() + "\n建议:请检查您使用的SOAP的版本号是否与服务器的一致。";
                    } else {
                        msg = e.getMessage();
                    }
                    Log.i(this.getClass().getSimpleName(), "IOException :" + msg);
                    //传递给Handler
                    Message message = kSoapHandler.obtainMessage();
                    message.obj = msg;
                    message.what = WHAT_KSOAP_ON_FAILURE;
                    kSoapHandler.sendMessage(message);
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }


    private Handler kSoapHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case WHAT_KSOAP_ON_FAILURE:
                    if (onKSoapListener != null) {
                        onKSoapListener.OnKSoapFailure((String) msg.obj);
                    }
                    break;
                case WHAT_KSOAP_ON_SUCCEED:
                    if (onKSoapListener != null) {
                        onKSoapListener.OnKSoapSucceed((String) msg.obj);
                    }
                    break;
            }
        }
    };


    /**
     * KSoap请求监听
     */
    public interface OnKSoapListener {

        void OnKSoapFailure(String error);

        void OnKSoapSucceed(String result);
    }


}

2.请求参数类[KSoapParameter ]:

import com.ice.android.File.FileUtils;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Relin
 * WebService的请求参数
 * on 2017/3/14.
 */


public class KSoapParameter {

    //字符串的参数
    private Map<String, String> stringParameter;
    //文件类型的参数
    private Map<String, File> fileParameter;

    /**
     * 添加字符串类型的参数
     *
     * @param key
     * @param value
     */
    public void addParameter(String key, String value) {
        if (stringParameter == null) {
            stringParameter = new HashMap<>();
        }
        stringParameter.put(key, value);
    }


    /**
     * 获取字符串参数
     *
     * @return
     */
    public Map<String, String> getStringParameter() {
        return stringParameter;
    }


    /**
     * 添加文件类型的参数
     *
     * @param key
     * @param value
     */
    public void addParameter(String key, File value) {
        if (fileParameter == null) {
            fileParameter = new HashMap<>();
        }
        if (FileUtils.getInstance().isImageFile(value)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
            String imageName = dateFormat.format(new Date()) + "png";
            String resultPath = FileUtils.getInstance().getCompressImageCachePath() + File.separator + imageName;
            value = FileUtils.getInstance().compressImage(value.getAbsolutePath(), resultPath, 100);
        }
        fileParameter.put(key, value);
    }


    /**
     * 获取文件类型的参数
     *
     * @return
     */
    public Map<String, File> getFileParameter() {
        return fileParameter;
    }

}


3.使用方法:

    KSoapParameter parameter = new KSoapParameter();
        parameter.addParameter("xtlb", "82");
        parameter.addParameter("jkxlh", Config.JKXLH);
        parameter.addParameter("jkid", "82C26");
        new KSoapUtils(Config.SERVICE, Config.SERVICE_NAMESPACE, SoapEnvelope.VER11).execute("queryObjectOut", parameter, new KSoapUtils.OnKSoapListener() {
            @Override
            public void OnKSoapFailure(String error) {


            }

            @Override
            public void OnKSoapSucceed(String result) {
                Log.i("RRL", this.getClass().getSimpleName() + "result:" + result);
            }
        });

猜你喜欢

转载自blog.csdn.net/u012127961/article/details/62889133