Click here to Skip to main content
15,886,689 members
Articles / Web Development / ASP.NET
Tip/Trick

ASP.NET Webservices in Java via kSOAP

Rate me:
Please Sign up or sign in to vote.
4.71/5 (4 votes)
5 Jan 2014CPOL2 min read 20.3K   7   6
Handy bridge between ASP.NET webservices and Java

Introduction

This tip shows a brief and handy way to consume ASP.NET webservices in Java Applications.

It can be useful in some applications like Android apps. Some time ago, I used it in a project to operate with certain .NET webservices (for example, Online-PDF Documents Generation) as well as and get some kind of data hosted in servers like SQL Server, all of this from outer applications from .NET Technologies.

Background

The main idea is that calling a webmethod between both platforms will just follow that simple syntax:

Image 1

and it will result in a simple managed code.

Calling a ASP.NET webservice in Java with this way just requires that the name we specify in Java matches the name of the webmethod.

Using the Code

How to Call

Calling ASP.NET webmethod in Java:

Java
String helloworld = MyWebservice.Query("HelloWorld");


ASP.NET Webmethod in C#

C#
[WebMethod]
public string HelloWorld()
{
    return "Hello World";
}

Parameters Flexibility

Of course, any bunch of parameters can be conveyed as well, so on the method can be used overloaded:

ASP.NET Webmethod in C#

C#
[WebMethod]
public string HelloPerson(string person)
{
    return "Hello " + person;          
}

While in Java, to include parameters to the request, we use the Parameter (implemented below) class:

Java
String response = 
    MyWebservice.Query(
        "HelloPerson", 
        new Parameter("person", "John", "person".getClass())); 

As you can see, the parameter name matches with the parameter name of the webmethod.

By default, the parameter type is String.

Of course, if there are several parameters, we also can use an array:

Java
Parameter[] parameters = new Parameter[2];
Parameters.Add(new Parameter("person", "John"));
Parameters.Add(new Parameter("city", "Madrid"));
String response = MyWebservice.Query("HelloPersonInCity", parameters);

ASP.NET webmethods can return plenty of types, all of them can be serialized in Java too, that´s the reason an Object type is always returned in Java Query Method. That leads us to our decision how to serialize them, one way might be JSON.

Referencing Webservices

We have to instantiate the AspNetWebservice class (implemented below) to specify the server where we'll realize method calls.

Java
AspNetWebservice MyWebservice = new AspNetWebservice("localhost/MyWebService.asmx");  

Or even specify the namespace and the soap action:

Java
AspNetWebservice MyWebservice = new AspNetWebservice(
        "http://tempuri.org/",
        "http://tempuri.org/",
        "localhost/MyWebService.asmx");

Full Implementation

Java
public class AspNetWebservice {
        public String SOAP_NAMESPACE;
        public String WSDL_TARGET_NAMESPACE;
        public String SOAP_ADDRESS;

        public static String DEFAULT_NAMESPACE = "http://tempuri.org/"; 
        public static String DEFAULT_ACTION_NAMESPACE = "http://tempuri.org/";

    public AspNetWebservice(String soapaddress){
    	this(DEFAULT_ACTION_NAMESPACE, DEFAULT_NAMESPACE, soapaddress);
    }   
    public AspNetWebservice(String sopaaction, String namespace, String soapaddress){
        SOAP_NAMESPACE= sopaaction;
        WSDL_TARGET_NAMESPACE = namespace;
        SOAP_ADDRESS = soapaddress;
    }
    public Object Query(string WebmethodName){
        return Query(WebmethodName, null);
    }
    public Object Query(String WebmethodName, Parameter[] parameters){
        SoapObject soapRequest = new SoapObject(WSDL_TARGET_NAMESPACE, WebmethodName);
        
        // The envelop request
        SoapSerializationEnvelope soapEnvelope = 
                    new SoapSerializationEnvelope(SoapEnvelope.VER11);
	
	//Enabling ASP.NET Webservices in Java
        soapEnvelope.dotNet = true;

        if(parameters != null){
            // The properties that will be passed as parameters
            PropertyInfo pi = new PropertyInfo();
            for(Parameter param: parameters){
                pi.setName(param.getName());
                pi.setValue(param.getValue());
                pi.setType(param.getType());
                // Assigning each property to the request
                soapRequest.addProperty(pi);
            }
        }

        soapEnvelope.setOutputSoapObject(soapRequest);

        HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
        Object response = null;
        try
        {
                     // Send the request via a customized call method
                    httpTransport.call(SOAP_NAMESPACE + WebmethodName, envelope);
                    // Getting the response
                    response = soapEnvelope.getResponse();
        }
        catch(Exception ex){
            return "It occurred an error in the request:\n" + ex.getMessage();
        }
        return response;
    }

    public class Parameter {
        private String Name;
        private String Value;
        private Object Type;
    public Parameter(String Name, String Value, Object type){
             this.Name = Name;
             this.Value = Value;
             this.Type = type;
       }
       public Parameter(String Name, String Value){
            this(Name, Value, String.Class);
       }
       public String getName(){
            return Name;
       }
       public String getValue(){
            return Value;
       }        
       public Object getType(){
            return Type;
       }
    }
}

The implementation of this is based in the use of kSoap library.

kSOAP is a SOAP web service client library for constrained Java environments such as Applets or J2ME applications (CLDC / CDC / MIDP).

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionI am getting file not found when i call this method. Pin
Member 1184298922-Jul-15 5:06
Member 1184298922-Jul-15 5:06 
QuestionI detect some errors Pin
pfernandes4-Jan-14 10:17
pfernandes4-Jan-14 10:17 
AnswerRe: I detect some errors Pin
User 102592174-Jan-14 10:56
User 102592174-Jan-14 10:56 
Thanks for your comment.

Property class is different from Parameter class, nonetheless both use these methods, I don´t see the problem.

Respect addProperty() method, it just requires one parameter wether it is Property class due to the object itself contains the value of the property.

GET_DATA: Ok, I overlooked that because of my code includes several constants that got the code parsed properly. Here, we have to specify the Webmethodname parameter.
SuggestionLooks Good! Pin
Paul Conrad3-Jan-14 9:16
professionalPaul Conrad3-Jan-14 9:16 
GeneralRe: Looks Good! Pin
User 102592173-Jan-14 9:59
User 102592173-Jan-14 9:59 
GeneralRe: Looks Good! Pin
Mohsin Azam4-Jan-14 4:56
Mohsin Azam4-Jan-14 4:56 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.