Summary of using KSOAP2 in WebService

The company’s server-side development is also drunk. The last project used webservice, and this project uses webservice again. Oh my god, I don’t know how to use HTTP. Okay, because I have a very bad memory, I used it last time. Forget it again, this time I will summarize it, because webservice uses the soap protocol, the official website gives the corresponding open source framework is ksoap2, so let’s summarize the usage of ksoap2

First step:Add dependencies to the project

Download the jar package of ksoap2, download link: download the jar package of ksoap2

< p>After the download is complete, add the jar package to your project

Step 2:Create one The tool class WebServiceUtil for network access

The call method in this class is specifically used to access WebService. In fact, the package of this class can be modified by yourself. There are many different types on the Internet. So, modify it according to your needs, I will post it below, you can encapsulate it yourself

/**  * WebServiceTools for access methods */ public class WebServiceUtils {// Is the server accessed bydotNetDevelopment  public static boolean isDotNet = true; // Thread The size of the pool, created here5pcs private static int threadSize = 5; // Create A reusable thread pool with a fixed number of threads, running these threads in a shared unbounded queue private static ExecutorService  threadPool = Executors.newFixedThreadPool(threadSize); / / Connection response mark public static final int SUCCESS_FLAG = 0; public static final int ERROR_FLAG = 1;  // In general, your own company development requires identity verification, of course you can also not verify it  private static final String ID_HEADERNAME = "verify method";// Identity verification method name private static final String ID_NAME_PARAM = "verify key1";// Identity Verification key  private static final String < em>ID_NA ME_VALUE = "verify value1";// Identity Verification value< /span> private static final String ID_PASSWORD_PARAM = "verify key2";// Identity Verification key  private static final String < em>ID_PASSWORD_VALUE = "verify value2";// Identity Verification value < em>/**  * CallWebServiceInterface, this method has only been accessed and usedJavaThe server written by me, I gave it here 5a parameter, in fact, the server address and namespace can be in this class The properties are written as constants, so you don’t need to give these two parameters every time you call, so there are only three parameters. *  * @param endPoint WebServiceServer address  * @param nameSpace Namespace(It's hard-coded on the server side, fixed, and you can see it in the server interface)  * < strong>@param methodName WebServiceCalling method name< span style="color:#629755; font-family:'宋体'"> * @param mapParams WebServiceThe parameter set can be< em>null  * @param reponseCallBack Server response interface,I have moved this interface to the outside to separate it out. In fact, it can be written in this tool class. Look at the bottom of the code and write this interface. In this tool class, this is also possible  */  public static void call(final String endPoint< span style="color:#cc7832">, final String nameSpace, final String methodName, SimpleArrayMap, String> mapParams, final ResponseInterface reponseCallBack) {// 1.< /span>CreateHttpTransportSEObject, passWebServiceServer address final HttpTransportSE transport = new HttpTransportSE(endPoint); < /span>transport.debug = true;  // Identity verification (If needed)// Element[] header = new Element[1];// // Pass in the namespace and verification method name/ / header[0] = new Element().createElement(nameSpace, ID_HEADERNAME);// // Create parameters 1// Element userName = new Element ().createElement(nameSpace, ID_NAME_PARAM);// userName.addChild(Node.TEXT, ID_NAME_VALUE);// header[0].addChild(Node.ELEMENT, userName);// // Create parameters 2// Element password = new Element().createElement(nameSpace, ID_PASSWORD_PARAM);// password.addChild(Node.TEXT, ID_PASSWORD_VALUE);// header[0].addChild(Node.ELEMENT, password);  // 2.CreateSoapObjectObject used to pass request parameters< /span> final SoapObject request = new SoapObject(nameSpace, methodName); // 2.1.Add parameters, or not pass if (mapParams != null span>) {for (int index =  0; index ; index++) {String key = mapParams.keyAt(index);// String value = mapParams.get(key); // In most cases, the parameters passed are  String < span style="color:#808080; font-family:'宋体'">Type, but in a few cases there will be boolean type, so use Object Replace Object value = mapParams.get(key); request.addProperty(key, value); }} // 3.InstantiateSoapSerializationEnvelope, incomingWebService< span style="color:#808080; font-family:'宋体'">的SOAPThe version number of the agreement  // here VER10 VER11 VER12 < span style="color:#808080; font-family:'宋体'">Three versions, fill in according to your needs final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11);// envelope.headerOut = header; // Identity verification (if required) envelope.dotNet =  isDotNet; // Set whether to call.NetDevelopedWebService envelope.setOutputSoapObject( request);// Passing parameters// envelope.bodyOut = request; //and the previous sentenceenvelope.setOutputSoapObject( request);equivalent // 4.Used for communication between the child thread and the main threadHandler, when the network request is successful, a message will be sent on the child thread, and then received on the main thread final Handler responseHandler = new Handler() {< span style="color:#bbb529">@Override public void handleMessage(Message msg) {super.handleMessage(msg); // According to the newsarg1value to determine which interface to call if  (msg.arg1 == SUCCESS_FLAG) {Log.e("WebServiceResult---", < /span>msg.obj.toString()); reponseCallBack.onSuccess ((SoapObject) msg.obj); //The interface used here isSoapObject, in fact, it can also beString, then write it as(String)msg.obj } else { reponseCallBack.onError((Exception) msg.obj);  }} }; < span style="color:#808080">// 5.Submit a child thread to the thread pool and in this thread Intraspecific callWebService if (threadPool == null || threadPool.isShutdown()) threadPool = Executors.newFixedThreadPool(threadSize); threadPool.submit (new Runnable() {@Override < /span>public void run() {SoapObject result = null;// String result = null;//The interface can beString  try { // < /span>ResolveEOFException System.setProperty("http.keepAlive", "false");< span style="color:#cc7832"> //  Connect to the server, some services may not need to be delivered NAMESPACE + methodName, the first parameter is passed null transport.call(nameSpace + methodName, envelope); if (envelope.getResponse()! = null) {// Get the response returned by the serverSoapObject result = (SoapObject) envelope.bodyIn;< span style="color:#808080">// SoapObject object = (SoapObject) envelope.bodyIn;// also in the interface Can YesString// result = object.getProperty(0).toString(); }} catch (IOException e) { // WhencallThe first parameter of the method isnullThere will be certain concepts to throw awayIOAbnormal // So you need to catch this exception and use the namespace plus the method name as a parameter to reconnect e.printStackTrace(); try { transport.call(nameSpace + methodName, envelope); if (envelope.getResponse() != null) {//  Get the response returned by the serverSoapObject result = (SoapObject) envelope.bodyIn;// SoapObject object = (SoapObject) envelope. bodyIn;//The interface can also beString// result = object.getProperty(0).toString(); }} < span style="color:#cc7832">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 { // Use the obtained newsHandlerSend to the main thread responseHandler.sendMessage(responseHandler.obtainMessage(0, SUCCESS_FLAG, 0, result)); span> }} }); }} }) span>} /**  * Set the size of the thread pool *   * @param threadSize  */  public static void setThreadSize (int threadSize) {WebServiceUtils.threadSize = threadSize; threadPool.shutdownNow();  threadPool = Executors.newFixedThreadPool(WebServiceUtils.threadSize); } < em>/**  * The server responds to the interface. You need to call back this interface after responding. This interface has been independently exported here. IninterfacesIn the package, so comment it out  */ // public interface Response {// public void onSuccess(SoapObject result); //The current one isSoapObject< span style="color:#808080; font-family:'宋体'">的//// public void onSuccess(String result);//Can also be usedstringrepresents//// public void onError(Exception e);// }}

At the back of the code, I commented out the Response interface. In fact, I put this interface into a separate class, as follows, just change I got a name and became ResponInterface, which is actually the same

import org.ksoap2.serialization.SoapObject;/** < em> * Created by jjg on 2016/10/18.  */ public interface ResponseInterface {public void onSuccess(SoapObject result ); public void onError (Exception e);}

The third step: With this tool class, it will be easy to handle, but I still创建了一个类,专门用来存放那些啥命名空间的、网络地址啥的,前面我说过,其实可以将这些放进WebServiceUtil工具类中,但为了方便和减少代码之间的耦合度,我还是单独给出了一个ServiceConstants类来存放这些常量,如下:

/**  * 这个类中存放的是一些服务常量,主要是一些服务器的接口链接  * Created by Eli on 2016/10/8.  */  public class ServiceConstants {    //服务器的接口总地址    public static final String URL_IMAGE= "http://justec.vicp.net:658";    // webservice服务器执行登入的地址    public static final String URL_BASE = "http://justec.vicp.net:658/ThermometerService.asmx?op=";    //web服务的命名空间    public static final String NAME_SPACE = "http://tempuri.org/";    //查询用户是否存在    /**  *   string    */  public static final String METHOD_USER_ISEXIST = "QueryUserIsExist";    //soap请求地址    public static final String SOAP_ACTION = "http://tempuri.org/QueryUserIsExist";    //用户登录    /**  *   string  string    */  public static final String METHOD_LOGIN = "UserLogin";    //用户注册    /**  *   string  string    */  public static final String METHOD_REGISTER = "UsersRegister";    //查询家庭用户是否存在    /**  *   string  int    */  public static final String METHOD_FAMILYISEXIST = "QueryUserFamilyIsExist";    //新增家庭用户    /**  *   string  int    */  public static final String METHOD_INSTER_FAMILY = "InsertUsersFamily";    //获取所有家庭成员信息    /**  *   int    */  public static final String METHOD_GET_FAMILY = "GetAllFamilyUsers";    //删除家庭用户    /**  * int  */  public static final String METHOD_DELETE_FAMILY = "DeleteUsersFamily";    /**  * 更新家庭成员信息  *   * string  *   */  public static final String METHOD_UPDATA_USER = "UpdateUsersFamily";    /**  * 更新家庭成员信息  *   * string  *   */  public static final < /span>String METHOD_UPDATA_MASTER= "UpdateUsers";}

看到了吗,因为我这里会用到很多服务端的方法名字,用户登入、用户注册等等都是有各自的方法名的,所以我在WebServiceUtil工具类中也将服务地址和命名空间放进Call参数中,因为我每次访问网络的地址是需要重新组织下的,而不是固定某一个不变的地址的,这样即使以后想要扩展其他网络接口,我可以直接在这里添加服务常量,然后组合成网络地址就可以调用Call方法直接使用了,要是你每次访问的服务地址是固定的,完全可以写成常量放进WebServiceUtil工具类中。

第四步:这一步也是为了编程的扩展性而添加的一个管理类,由于网络端访问的方法名很多,所以我写了个管理类来管理,就像MVP思想一样,我只需要在V层调用一个方法,具体的一些逻辑思路都是M层完成一个道理

/**  * 这个类是个操作服务器的类,一系列的登入,注册,删除,查询等等方法集中在这里,可以直接来调用  * Created by jjg on 2016/10/18.  */ public class Login_manager {    private static Login_manager instance;//实例    public static synchronized Login_manager getInstance() {//获取实例,下次用到这个类不用使用new来创建对象,直接Login_manager.getInstance()就可以        if (instance == null) {            instance = new Login_manager();        }        return instance;    }    private Login_manager() {//构造方法    }    /**  * 注册密码MD5加密(就是注册完毕后将密码加密后上传给服务器,以防原始密码在传送过程中被别人盗用,这样保证密码不会泄露)  *  * @param info  * @return  */  public String getMD5(String info) {//给的参数是个String,经过加密后返回的也是一个String        try {            MessageDigest md5 = MessageDigest.getInstance("MD5");            md5.update(info.getBytes("UTF-8"));            byte[] encryption = md5.digest();            StringBuffer strBuf = new StringBuffer();            for (int i = 0; i < encryption.length; i++) {                if (Integer.toHexString(0xff & encryption[i]).length() == 1) {                    strBuf.append("0").append(Integer.toHexString(0xff & encryption[i]));                } else {                    strBuf.append(Integer.toHexString(0xff & encryption[i]));                }            }            return strBuf.toString();        } catch (NoSuchAlgorithmException e) {            return "";        } catch (UnsupportedEncodingException e) {            return "";        }    }    /**  * 请求登入  * @param context  * @param userName  * @param pwd  * @param responseInterface  */  public void requestLogin(Context context, final String userName, final String pwd, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userN ame", userName + "");        mapParams.put("password", getMD5(pwd));        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在登陆...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_LOGIN,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_LOGIN, mapParams,                new ResponseInterface() {                    @Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e);                    }                });    }    /**  * 检测用户是否存在(检测的是注册的那个管理员用户)  *  * @param context  * @param userName  * @param responseInterface  */  public void requestUserIsExist(Context context, final String userName, ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userName", userName + "");        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_USER_ISEXIST,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_USER_ISEXIST, mapParams,                responseInterface);    }    /**  * 请求注册  * @param context  * @param userName < span style="color:#8a653b"> * @param pwd  * @param iamge  * @param responseInterface  */  public void requestRegister(Context context, final String userName, final String pwd,final String iamge, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userName", userName + "");        mapParams.put("password", getMD5(pwd));        mapParams.put("image", iamge);        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在注册...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_REGISTER,                ServiceConst ants.NAME_SPACE, ServiceConstants.METHOD_REGISTER, mapParams,                new ResponseInterface() {                    @Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e);                    }                });    }    /**  * 请求添加家庭成员    string< /userName>  string  int  string    *  * @param context  * @param userName  * @param userId  * @param responseInterface  */  public void requestAddFamily(Context context, final String userName, final String realName,final String sex,final String age,final int userId, final String imgUrl, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userName", userName);        mapParams.put("realName",realName);        mapParams.put("sex",sex);        mapParams.put(< span style="color:#6a8759">"birthday",age);        mapParams.put("userID", userId + "");        mapParams.put("image", imgUrl);        Log.e("image-------", imgUrl.length() + "----" + imgUrl);        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在增加用户...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_INSTER_FAMILY,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_INSTER_FAMILY, mapParams,                new ResponseInterface() {                    @Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss() ;                        responseInterface.onError(e);                    }                });    }    /**  * 查询家庭用户是否存在  *  * @param context  * @param userName  * @param userId  * @param responseInterface  */  public void requestFamilyIsExist(Context context, final String userName, final int userId, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userName", userName + "");        mapParams.put("userID", userId + "");        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在查询用户是否存在...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_FAMILYISEXIST,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_FAMILYISEXIST, mapParams,                new ResponseInterface() {                    @ Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e) ;                    }                });    }    /**  * 删除家庭成员  *  * @param context  * @param userId  * @param < em>responseInterface  */  public void requestDeleteUserFamily(Context context, final int userId, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userFamilyID", userId + "");        final ProgressDialog dia log2 = ProgressDialog.show(context, null, "正在删除用户...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_DELETE_FAMILY,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_DELETE_FAMILY, mapParams,                new ResponseInterface() {                    @Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e);                    }                });    }    /**  * 获取所有家庭成员信息  *  * @param context   * @param userId  * @param responseInterface  */  public void requestGetFamily(Context context, final int userId, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("userID", userId + "");        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在获取用户...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(Ser viceConstants.URL_BASE + ServiceConstants.METHOD_GET_FAMILY,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_GET_FAMILY, mapParams,                new ResponseInterface() {                    @Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e);                    }                });    }    /**  * 更新家庭成员信息  *   * string  *   *  * UpdateUsersFamilyResult  */  public void requestUpdateUsers(Context context, final String strJson, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("strJson", strJson + "");        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在修改信息...");        < /span>dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_UPDATA_USER,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_UPDATA_USER, mapParams,                new ResponseInterface() {                    @Overrid e                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e);                    }                });        Log.e("经过联网向服务器发送过去了Json字符串","服务器将返回修改成功或者失败");    }    /**  * 更新主用户信息  *   * string  *   *  * UpdateUsersFamilyResult  */  public void requestUpdateMaster(Context context, final String strJson, final ResponseInterface responseInterface) {        // 参数集合        SimpleArrayMap mapParams = new SimpleArrayMap();        mapParams.put("strJson", strJson + "");        final ProgressDialog dialog2 = ProgressDialog.show(context, null, "正在修改信息...");        dialog2.setCancelable(true);        dialog2.setCanceledOnTouchOutside(false);        WebServiceUtils.call(ServiceConstants.URL_BASE + ServiceConstants.METHOD_UPDATA_MASTER,                ServiceConstants.NAME_SPACE, ServiceConstants.METHOD_UPDATA_MASTER, mapParams,                new ResponseInterface() {                    @Override                    public void onSuccess(SoapObject result) {                        dialog2.dismiss();                        responseInterface.onSuccess(result);                    }                    @Override                    public void onError(Exception e) {                        dialog2.dismiss();                        responseInterface.onError(e);                    }                });    }}

好了,现在直接可以在Activity中使用了

第五步:开始使用

使用的话我就以登入为例吧,可以直接在Activity中这样调用

Login_manager.getInstance().requestLogin(this, username, usercode, new ResponseInterface() {    @Override    public void onSuccess(SoapObject result) {    String strResult=result.getPrimitivePropertyAsString("UserLoginResult");    < /span>JSONArray jsonArray = null;        int userID = 0;//这个userID是连接成功后返回的管理员ID,需要保存起来,在刷新数据的时候会用到        try {            jsonArray = new JSONArray(strResult);            userID = jsonArray.getJSONObject(0).getInt("ID");        } cat ch (JSONException e) {            e.printStackTrace();        }        if (userID > 0) {            Toast.makeText(Login_Activity.this, "登录成功!", Toast.LENGTH_SHORT).show();            saveUserMaster(userID, username);            Intent intent = new Intent(Login_Activity.this, UserActivity.class);            startActivity(intent);            finish();        } else {            Toast.makeText(Login_Activity.this, "登录失败,用户名或密码错误!", Toast.LENGTH_SHORT).show();        }    }    @Override    public void onError(Exception e) {    }});

好了,要是没看懂,多看几遍,然后找个服务端口实践下,我这里的服务端口好像已经没有用了,服务已经关闭了。

Leave a Comment

Your email address will not be published.