Encapsulation of ksoap2-android-based soap

Source: Internet
Author: User
Tags soap

Instance based on Ksoap2-android-assembly-3.3.0-jar-with-dependencies.jar

1: Defines the callback interface, which determines the return value type by generic type

Package com.ciii.bd.electrombile.soap;

/**
* Processing the callback interface of the request server
* Created by Lipanquan on 2016/12/26.
*/
public class Soapcallback<responseresult> {
/**
* Result of request failed processing, Run main thread
*/
public void Onfailresult () {

}

/**
* Result of request successful processing, Run main thread
*
* @param The result of Responseresult request successfully processed
*/
public void Onresponseresult (Responseresult responseresult) {

}

/**
* Onresponseresult method after execution
*/
public void onfinally () {

}
}

2: The tool class that handles SOAP requests, with reflection and generic mates that direct callbacks to the caller to specify the result of the generic type

Import Android.os.Handler;
Import Android.os.Looper;
Import Android.os.Message;

Import Com.ciii.base.utils.GsonUtils;
Import Com.ciii.bd.electrombile.okhttp.OkHttpCallback;

Import Org.ksoap2.SoapEnvelope;
Import Org.ksoap2.serialization.SoapObject;
Import org.ksoap2.serialization.SoapPrimitive;
Import Org.ksoap2.serialization.SoapSerializationEnvelope;
Import Org.ksoap2.transport.HttpTransportSE;

Import Java.lang.reflect.Field;
Import Java.lang.reflect.Method;
Import java.util.ArrayList;
Import Java.util.Iterator;
Import Java.util.Map;

/**
* Tool class for processing SOAP requests
* Created by Lipanquan on 2016/12/26.
*/
public class Soapnetutils {

/**
* Request processing of Successful callback indicator
*/
private static Final intmessage_post_success = 0x1;

/**
* Callback flag for request processing failed
*/
private static Final intMessage_post_fail = 0x2;

/**
* Name space
*/
private static StringNamespace

/**
* Address of the server
*/
private static StringUrl

Private Soapnetutils () {
}

private static SoapnetutilsInstance = new Soapnetutils ();

/**
* Get the tool class for processing SOAP requests
*
*@returnTool class for processing SOAP requests
*/
public static Soapnetutils getinstance () {
ReturnInstance
}

/**
* Initialize the SOAP protocol Request tool class object
*
*@paramNamespaceName space
*@paramwr.The address of the server
*/
public void Initsoap (string namespace, string url) {
Soapnetutils.namespace = namespace;
Soapnetutils.url = URL;
if (soapnetutils.namespace = = NULL | | Soapnetutils.Namespace.equals ("") | |
Soapnetutils.URL = = NULL | | Soapnetutils.Url.equals ("")) {
throw new RuntimeException ("namespace cannot be empty, and the URL cannot be empty. Initializing the SOAP protocol Request tool class object failed ");
}
}

/**
* Execute Request
*
*@paramTSpecifies the class object file that returns the result
*@paramUrltypeType of marking requested
*@paramParametersParameter list
*@paramCallbackcallback function
* @param <T> Specifies the class object file that returns the result
*/
public <T> void Dosoaprequest (Final class<t> T, final String Urltype, Final map<string, object> parameters, final Soapcallback callback) {
if (Soapnetutils.namespace = = NULL | | Soapnetutils. namespace.equals ("") | |
Soapnetutils. url = = NULL | | Soapnetutils. url.equals ("")) {
throw new RuntimeException ("Initsoap (string namespace, string url) method initializes the SOAP protocol request tool class and then uses ...");
}
New Thread (new Runnable () {
@Override
public void Run () {
try {
T result = Dosoap (T, Urltype, p Arameters, callback);
Send message to main thread successful, getteladdress function completed
Message msg = message.Obtain ();
Msg.what =message_post_success;
Msg.obj = new Myexecutetaskresult<t> (callback, result);
GetHandler (). SendMessage (msg);
} catch (Exception e) {
Send message to main thread successful, getteladdress function completed
Message msg = message.Obtain ();
Msg.what =Message_post_fail;
Msg.obj = new Myexecutetaskresult<t> (callback, NULL);
GetHandler (). SendMessage (msg);
}
}
}). Start ();
}

/**
* True execution of network requests
*
*@paramTSpecifies the class object file that returns the result
*@paramUrltypeType of marking requested
*@paramParametersParameter list
*@paramCallbackcallback function
*@param <T>Specifies the class object file that returns the result
*/
Private <T> T Dosoap (class<t> T, String Urltype, map<string, object> parameters, Soapcallback callback) Throws Exception {
Object instance = T.newinstance ();
Soapobject Soapobject = new
Soapobject (namespace, urltype);//"Userlogin" creates a Soap object
Set properties that are passed to the server through the SOAP protocol
Iterator<map.entry<string, object>> it = Parameters.entryset (). Iterator ();
while (It.hasnext ()) {
map.entry<string, object> Entry = It.next ();
if (Entry.getvalue () instanceof ArrayList) {
Soapobject parametervalue = new Soapobject ();
for (String str: (arraylist<string>) Entry.getvalue ()) {
Parametervalue.addproperty ("Long", long.)ValueOf (str));
}
Soapobject.addproperty (Entry.getkey (), parametervalue);
} else
Soapobject.addproperty (Entry.getkey (), Entry.getvalue ());
}
Soapserializationenvelope envelope = new Soapserializationenvelope (
SoapEnvelope.VER11);
Envelope.bodyout = Soapobject;
Envelope.dotnet = true;
Envelope.setoutputsoapobject (Soapobject);
Httptransportse Httptransportse = new Httptransportse (URL);
try {
Invoke Service
Httptransportse.call (namespace + urltype, envelope);
} catch (Exception e) {
E.printstacktrace ();
}
if (Envelope.bodyin instanceof Soapobject) {
Soapobject response = (soapobject) Envelope.bodyin;
field[] fields = Instance.getclass (). Getdeclaredfields ();
for (int i = 0; i < fields.length; i++) {
Fields[i].setaccessible (TRUE);
class<?> type = Fields[i].gettype ();
Object Fieldvalue;
try {
Fieldvalue = Response.getproperty (Fields[i].getname ());
} catch (Exception e) {
Continue
}
Object o;
if (fieldvalue instanceof soapprimitive) {
o = gsonutils.GetInstance (). J2O (Fieldvalue.tostring (), type);
Fields[i].set (instance, O);
} else if (Fieldvalue instanceof Soapobject) {
if (type = = Arraylist.class) {
Soapobject object = (soapobject) fieldvalue;
o = new ArrayList ();
Method m = O.getclass (). GetMethod ("Add", Object.class);
for (int j = 0; J < Object.getpropertycount (); j + +) {
Soapprimitive primitive = (soapprimitive) object.getproperty (j);
M.invoke (O, Primitive.getvalue ());
}
Fields[i].set (instance, O);
}
Continue
} else {
Continue
}
Fields[i].set (instance, O);
}
}
Return (T) instance;
}
private static Internalhandler Shandler;
private static Handler GetHandler () {
Synchronized (Okhttpcallback.class) {
if (Shandler = = null) {
Shandler = new Internalhandler ();
}
return shandler;
}
}
private Static Class Myexecutetaskresult<result> {
@SuppressWarnings ("Rawtypes")
Final Soapcallback Mtask;
Final Result Mdata;
Public Myexecutetaskresult (Soapcallback task,
Result data) {
Mtask = task;
Mdata = data;
}
}
private static class Internalhandler extends Handler {
Public Internalhandler () {
Super (Looper.getmainlooper ());
}
@SuppressWarnings ("Unchecked")
@Override
public void Handlemessage (Message msg) {
myexecutetaskresult<?> result = (myexecutetaskresult<?>) msg.obj;
Switch (msg.what) {
Case Message_post_success:
Result.mTask.onResponseResult (Result.mdata);
Break
Case Message_post_fail:
Result.mTask.onFailResult ();
Break
}
Result.mTask.onFinally ();
}
}
}
3: Use
Soapnetutils.getinstance (). Dosoaprequest(User.class,Url_type_login, parameters, new soapcallback<user> () {
@Override
public void Onresponseresult (user user) {
if (user.isloginsuccessed ()) {
User.setusername (Et_login_username.gettext (). toString ());
Save user name and password
Putstring (Spkey.key_username, Et_login_username.gettext (). toString (). Trim ());
if (isautologin)
putstring (Spkey. Key_password, Et_login_password.gettext (). toString (). Trim ());
Getmyapplication (). Setcurrentuser (user);
Showtoastshort (R.string. toast_login_success);
Startenteractivity (Selectdevicelistactivity.class, true);
} else {
Showtoastshort (r.string. Toast_login_fail);
}
}

@Override
public void Onfailresult () {
Showtoastshort (R.string.toast_login_fail);
}

@Override
public void onfinally () {
btn_login.setenabled (true);
Dismissmdialog ();
}
});

Encapsulation of ksoap2-android-based soap

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.