Click here to Skip to main content
15,396,032 members
Articles / Programming Languages / Java / Java SE / J2EE
Article
Posted 6 Jan 2009

Tagged as

Stats

305.9K views
3.8K downloads
71 bookmarked

How to Invoke Java Web Service in ASP.NET using C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (35 votes)
6 Jan 2009CPOL10 min read
Web Services Interoperability

Contents

Background

According to W3C

A Web Service is a software system designed to support interoperable machine-to-machine interaction over a network:

  1. It has an interface described in a machine-processable format (specifically WSDL).
  2. Other systems interact with the web service in a manner prescribed by its description using SOAP messages, typically conveyed using HTTP with an XML serialization in conjunction with other Web standards.

Features of Web Services

  1. Web services operate over any network (the Internet or a private Intranet) to achieve specific tasks.
  2. The tasks performed by a web service are methods or functions that other applications can invoke and use.
  3. Web service requests/responses can be sent/received between different applications on different computers belonging to different businesses.

A Web Service Includes Three Basic Components

  1. A mechanism to find and register interest in a service
  2. A definition of the service’s input and output parameters
  3. A transport mechanism to access a service

Web services also include other technologies that can be used to provide additional features such as security, transaction processing and others.

Web Services Interoperability

Much of the promise of web services is its potential for seamless interoperability across heterogeneous systems, platforms, applications, and programming languages. Interoperability is a primary goal of web services. However, it is not a given. Web services standards facilitate interoperability, but do not ensure it. Many considerations and issues need to be resolved to achieve full interoperability. As the number of specifications expands to address gaps, so do the interoperability challenges.

A web service has many potential clients, and this array of clients can use a variety of libraries and providers to connect. Services can, in turn, become clients of other services. Ensuring that clients based on different implementations of the standards can interoperate with the service is critical to the service's success.

The primary goal of this article is to demonstrate how to create Java web service and invoke it from ASP.NET (C#) application.

Here, we shall develop simple mathematical functions like addition, subtraction, etc. using Java web services called JSimpCalcWebService. Later, we shall demonstrate how to invoke these web service methods through ASP.NET with C# called JSimpCalcWebServiceWebSite. To create there two separate applications, we need to use two IDEs. Here in this example, we use NetBeans 6 for Java web service and Visual Studio 2008 for the ASP.NET web service client which invokes the web service.

Create a Java Web Service

Netbeans 6 provides a very easy and convenient way to develop web service. There are a few steps involved in developing a web service using it. These steps can be summarized as follows:

  1. Create a web application project
  2. Add web service to the project
  3. Add operations to the web service
  4. Implementing the web methods
  5. Deploy and test the web service

Step 1. Create a Web Application Project

  1. Start the Netbeans IDE; go to the New Project which is available under File menu. The New Project wizard opens.
  2. Select the web from categories options and web application from project section and then press the next button.

    Invoke_Java_WS_In_CS/01.CreateWebServiceNetbeansChooseWebAppProject.png

    Figure One: Create New Project Step 1
  3. On the next screen, mention the project name, select the project location. We can also mention the server name in which we want to deploy our web application as well we can change the default context path.

    Here, we mention the project name JSimpCalcWebService and keep the context path the same as project name. We use GlassFish V2 application server for deployment.

    Create Web Service Netbeans Project
    Figure Two: Create New Project Step 2
  4. Now, click the finish button.

Step 2. Add Web Service to the Project

  1. Right click on the project name in the Projects explorer window.

    Create Web Service Netbeans Menu

    Figure Three: Web Service Menu Option
  2. From the context menu options, select the Web Service menu. A web service dialog opens.

    Create Web Service Netbeans Web Serice Name

    Figure Four: Add New Web Service
  3. Mention the web service name and the package name as mentioned in the image below, and then click the finish button.

    In our example, the web service name is JSimpCalcWebService and the package name is calc.ws.

Step 3. Add Operations to the Web Service

After we add web service to our application, now it's time to add web service operation or WebMethod. We can do it in two possible ways, one is through design mode and another is through source mode. In our example, we use design mode for creating a skeleton of WebMethod in the easiest way.

Create Web Service Netbeans WS Add Operation Button

Figure Five: Add Operation To Web Service
  1. As we can see from the highlighted section in figure five, we can add web service operations by clicking Add Operation button. It opens a Add Operation dialog box. Please refer to figure six.

    Create Web Service Netbeans WS Add Operation

    Figure Six: Add Parameters To Web Operation
  2. In the Add Operation dialog, we must mention name (which is actually a WebMethod name).
  3. We can also enter parameter names and their types (these parameters are known as WebParam).

    In figure six, we mention the WebMethod name as addition whose return type is java.lang.String and it takes two parameters (parameter1. and parameter2) of type double. Similarly, we create other operations as well like subtraction, multiplication, division, power, maximum, minimum.

Step 4: Implementing the Web Methods

Once we finish step three, a basic structure of our web service should be ready. Then we switch from design mode to source mode as shown in figure seven to do rest of the implementation.

Create Web Service Netbeans WS Source Mode

Figure Seven: Write The Code For The Web Service

The code should look like follows:

Java
package calc.ws;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
import calc.util.NumberFormater;

/**
 * @author Bikash Shaw
 */
@WebService()
public class JSimpCalcWebService {

/**
     * Web service operation
     */
    @WebMethod(operationName = "addition")
    public String addition(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format((parameter1 + parameter2),0,6);
    }

/**
     * Web service operation
     */
    @WebMethod(operationName = "subtraction")
    public String subtraction(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format((parameter1 - parameter2),0,6);
    }

/**
     * Web service operation
     */
    @WebMethod(operationName = "multiplication")
    public String multiplication(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format((parameter1 * parameter2),0,6);
    }

/**
     * Web service operation
     */
    @WebMethod(operationName = "division")
    public String division(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format((parameter1 / parameter2),0,6);
    }

/**
     * Web service operation
     */
    @WebMethod(operationName = "power")
    public String power(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format(Math.pow(parameter1, parameter2),0,6);
    }

/**
     * Web service operation
     */
    @WebMethod(operationName = "maximum")
    public String maximum(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format(Math.max(parameter1, parameter2),0,6);
    }

/**
     * Web service operation
     */
    @WebMethod(operationName = "minimum")
    public String minimum(@WebParam(name = "parameter1")
    double parameter1, @WebParam(name = "parameter2")
    double parameter2) {
        //TODO write your implementation code here:
        return NumberFormater.format(Math.min(parameter1, parameter2),0,6);
    }
} 
Source One: Java JSimpCalcWebService.java Web Service Source Code

Here, we use NumberFormater.format(double number, int minFractionDigits,

int maxFractionDigits) method to format the double value to java.lang.String up to six decimal point. Refer to source two.

Java
package calc.util;

import java.text.NumberFormat;

/**
 * @author Bikash Shaw
 */
public class NumberFormater {

    public static String format(double number, int minFractionDigits,
            int maxFractionDigits) {
        NumberFormat format = NumberFormat.getInstance();
        format.setMaximumFractionDigits(maxFractionDigits);
        format.setMinimumFractionDigits(minFractionDigits);
        return format.format(number);
    }
}
Source Two: NumberFormater.java Source Code

Step 5. Deploy and Test the Web Service

Now our web service is ready for deployment and test. With Netbeans 6, it can be achieved with very few steps. First, make sure that the GlassFish server is running. To start the server, we need to perform the following steps:

  1. Go to Services explorer window.
  2. Expand the Servers node.
  3. Right click on the server name (in our case, its GlassFish V2). A context menu pops up.
  4. Select Start from the menu options.

Create Web Service Netbeans Start Up Server

Figure Eight: Start GlassFish V2 Application Server

Now, as our server is running, it's time to deploy the application and test the web service that we have developed. Netbeans does the deployment for us with few mouse clicks, mentioned as follows:

  1. Go to Projects explorer window.
  2. Expand the Web Services node.
  3. Right click on the web services name (in our case, its JSimpCalcWebService). A context menu pops up.
  4. Click the Test Web Service menu.

Create Web Service Netbeans Test Web Service

Figure Nine: Test Web Service

The above mentioned steps deploy the application and lunch the default browser in which the web service can be tested via SOAP request and response. Please refer to figure ten for sample output. We can also view the WSDL (Web Services Description Language) file by clicking on the hyperlink.

Create Web Service Netbeans Web Service Tester

Figure Ten: Test Web Service

Alternatively, we can test the web service and view its WSDL document through our GlassFish application server’s admin console as shown in figure eleven.

Create Web Service Admin Consol Web Service Tester

Figure Eleven: Test Web Service via Admin Consol

Once we click on the View WSDL link, we can view an XML file for describing our web service. The WSDL file should look like figure twelve.

Create Web Service WSDL File

Figure Twelve: WSDL File

The URL shown at the address bar will require invoking the web service. We shall demonstrate its usage during creating of our web application using ASP.NET.

Create ASP.NET Web Site Using C#

Now, our web service is ready to get invoked from non Java based development platform. In this article, we develop a sample ASP.NET based client. Using Visual Studio 2008, it can be achieved in few steps, which can be summarized as follows:

  1. Create ASP.NET web site.
  2. Add web reference.
  3. Write code to invoke web service.
  4. Test web service client application.

Step 1. Create ASP.NET Web Site

  1. Start Visual Studio 2008; go to the New Web Site… which is available under File menu.

    Create Web Service Client New Web Site Window

    Figure Thirteen: New Web Site Window
  2. Select ASP.NET Web Site.
  3. Select the folder in which we want to create the web site. In our case, it’s JSimpCalcWebServiceWebSite
  4. Select the language Visual C# and click OK button.

Step 2. Add Web Reference

Now we need to mention the WSDL file in our web site. To add the web service reference, we must perform the following steps:

  1. Go to Solution Explorer window.
  2. Right click on the project name (in our case, it's JSimpCalcWebServiceWebSite). A context menu pops up.
  3. Click the Add Web Reference menu. The Add Web Reference dialog opens.

    Create Web Service Client Add Web Reference context menu

    Figure Fourteen: Add Web Reference Context Menu
  4. Copy and paste the WSDL URL from our web browser’s address bar (refer to figure twelve) to Add Web Reference dialog’s address bar and press go button (refer to figure fifteen).

    Create Web Service Client Add Web Reference context menu

    Figure Fifteen: Add Web Reference Dialog
  5. We can see all the methods names of our web service. Give a name to the web reference (in this example, it's JSimpCalcWebService) and click the Add Reference button.

Step 3. Write Code to Invoke Web Service

Using C#, we can very easily invoke the web service with few lines of code:

  1. We first design an ASP.NET page. The default fie name is Default.aspx (the source is available in zip file).
  2. Induce the web reference in to our code (i.e., Default.aspx.cs). For example:
    Java
    using JSimpCalcWebServiceService;
  3. Next, create the object of the web reference.
    Java
    JSimpCalcWebServiceService.JSimpCalcWebServiceService proxy = 
                  new JSimpCalcWebServiceService.JSimpCalcWebServiceService();
  4. Now, we can access the WebMethod like any other method call. For example:
    Java
    proxy.addition(10,20);
    Create Web Service Client C# Code
    Figure Sixteen: Web Methods Invocation Code

The code should look like follows:

Java
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using JSimpCalcWebServiceService;

public partial class _Default : System.Web.UI.Page 
{
    JSimpCalcWebServiceService.JSimpCalcWebServiceService proxy;

    protected void Page_Load(object sender, EventArgs e)
    {
        proxy = new JSimpCalcWebServiceService.JSimpCalcWebServiceService();
    }

    protected void btnAddition_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultAddition.Text = "Result: " + 
                   proxy.addition(double.Parse(txtbtnAdditionParameter1.Text), 
								double.Parse(txtbtnAdditionParameter2.Text));
        }
        catch (FormatException)
        {
            lblResultAddition.Text = "Result: Invalide Input";
        }
        UpdatePanelAddition.Update();
    }

    protected void btnSubtraction_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultSubtraction.Text = "Result: " + 
                 proxy.subtraction(double.Parse(txtSubtractionParameter1.Text), 
									double.Parse(txtSubtractionParameter2.Text));
        }
        catch(FormatException)
        {
            lblResultSubtraction.Text = "Result: Invalide Input";
        }

        UpdatePanelSubtraction.Update();
    }
    protected void btnMultiplication_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultMultiplication.Text = "Result: " + 
               proxy.multiplication(double.Parse(txtMultiplicationParameter1.Text), 
									double.Parse(txtMultiplicationParameter2.Text));
        }
        catch (FormatException)
        {
            lblResultMultiplication.Text = "Result: Invalide Input";
        }

        UpdatePanelMultiplication.Update();
    }

    protected void btnDivision_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultDivision.Text = "Result: " + 
                proxy.division(double.Parse(txtDivisionParameter1.Text), 
								double.Parse(txtDivisionParameter2.Text));
        }
        catch (FormatException)
        {
            lblResultDivision.Text = "Result: Invalide Input";
        }

        UpdatePanelDivision.Update();
    }

    protected void btnMaximum_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultMaxMin.Text = "Result: " + 
                   proxy.maximum(double.Parse(txtMaxMinParameter1.Text), 
							double.Parse(txtMaxMinParameter2.Text));
        }
        catch (FormatException)
        {
            lblResultMaxMin.Text = "Result: Invalide Input";
        }

        UpdatePanelMaxMin.Update();
    }

    protected void btnMinimum_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultMaxMin.Text = "Result: " + 
                    proxy.minimum(double.Parse(txtMaxMinParameter1.Text),
								double.Parse(txtMaxMinParameter2.Text));
        }
        catch (FormatException)
        {
            lblResultMaxMin.Text = "Result: Invalide Input";
        }

        UpdatePanelMaxMin.Update();
    }

    protected void btnPower_Click(object sender, EventArgs e)
    {
        try
        {
            lblResultPower.Text = "Result: " + 
                       proxy.power(double.Parse(txtPowerParameter1.Text), 
							double.Parse(txtPowerParameter2.Text));
        }
        catch (FormatException)
        {
            lblResultPower.Text = "Result: Invalide Input";
        }

        UpdatePanelPower.Update();
    } 
}
Source Three: Default.aspx.cs Source Code

Step 4. Test Web Service Client Application

Now, it's time to test our web service client application by clicking on the Start Debugging toolbar button or by pressing F5 key. The web page should look like the figure below:

Create Web Service Client Web Application Output

Figure Seventeen : Web Site Output

Conclusion

This article tried to demonstrate standards used by web services with little concern for the underlying implementation mechanism. The example shown here exploits a number of properties of web services mentioned below:

  • Self-Contained: No additional software is required for web service:
    1. Client-Side: A programming language with XML/HTML client support
    2. Server-Side: A web server and a SOAP server are needed
  • Loosely Coupled: Client and server only knows about messages - a simple coordination level that allows for more flexible re-configuration.
  • Web-Enabled: Web Service are published, located and invoked across the web, using established lightweight Internet standards.
  • Language-Independent and Interoperable: Client and server may be implemented in different environments and different languages.
  • Composable: Web service can be aggregated using workflow techniques to perform higher-level business functions.
  • Dynamically Bound: With UDDI and WSDL, the discovery and binding of web services can be automated.
  • Programmatic Access: The web services approach does not provide a graphical user interface but operates at the command level.
  • Wrap Existing Applications: Stand-alone applications can easily be integrated by implementing a web service as an interface.

Similarly, we can create web services in C# and can be invoked by Java web service client application.

License

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

Share

About the Author

Bikash Shaw
Software Developer (Senior) Société Générale
India India
Summary:

1. Extensive working experience in web and windows application development, database programming using Java and .Net technologies.

2. Good knowledge in SDLC and Processes like project planning, requirement gathering, development, test planning, release management and production support.

3. Good knowledge and working experience in following methodologies:
a. Agile Development Approach
b. Test Driven Development
c. Behavior Driven Development
d. Continuous Integration & Delivery Model.

4. Excellent communication & analytical skills, good team player, great mentoring capability.

5. Interaction with customer and team spread over different geographical area.

Technologies / Languages: J2SE 5/6, J2EE, .Net 2.0/3.5, C#, ASP.NET, AJAX, XHTML, CSS, JavaScript, jQuery, PL/SQL, Web Services (SOAP based), Winforms, Hibernate, Spring, GWT, XML, XSD, XPath, SAX, JAXB, JUnit, JBehave, Mockito, Selenium, StringTemplate, Log4J, Apache Commons API

Database: Oracle, SQL Server, MySQL, Sybase

Application Server: Tomcat, Sun Application Server, JBoss, GlassFish, Jetty, IIS

Development Environments: Eclipse, NetBeans, Visual Studio.

Designing Tools: Enterprise Architect, Microsoft Visio

Version Control: SVN, Perforce

Build Management: Hudson & JCruisemonitor, TeamCity

Bug Tracking Tools: HP Quality Center, Bugzilla, JIRA

Specialties:
1. Agile Test and Behavior Driven Development
2. Continuous Delivery Approach
2. Spring IOC and MVC
3. Web Services

Comments and Discussions

 
QuestionHow-to-invoke-Java RESTful-web-service-in-ASP-net-using-C Pin
Member 1458759920-Sep-19 8:26
MemberMember 1458759920-Sep-19 8:26 
GeneralGood articale Pin
bhavana.patel13-Feb-13 4:03
Memberbhavana.patel13-Feb-13 4:03 
Questionconsume java web service in asp.net 2.0 RPC/MIME Pin
Member 394398831-Oct-12 0:27
MemberMember 394398831-Oct-12 0:27 
QuestionThank and question Pin
Lechu8131-May-12 8:29
MemberLechu8131-May-12 8:29 
QuestionMy vote of 5 Pin
Herman Bakker1-Jan-12 19:11
MemberHerman Bakker1-Jan-12 19:11 
QuestionCommunication using HTTS Pin
PetoG13-Oct-11 2:27
MemberPetoG13-Oct-11 2:27 
GeneralMy Vote 5 Pin
User 62554641-Oct-11 0:48
MemberUser 62554641-Oct-11 0:48 
Generalquestion regarding java wsdl Pin
mlov831-Dec-10 17:07
Membermlov831-Dec-10 17:07 
GeneralRe: question regarding java wsdl Pin
Bikash Shaw28-Dec-10 21:19
MemberBikash Shaw28-Dec-10 21:19 
Questionhow to invoke the java web service in a XNA game studio. Pin
tonybrant29-Oct-10 17:22
Membertonybrant29-Oct-10 17:22 
AnswerRe: how to invoke the java web service in a XNA game studio. [modified] Pin
Bikash Shaw30-Oct-10 0:22
MemberBikash Shaw30-Oct-10 0:22 
GeneralRe: how to invoke the java web service in a XNA game studio. Pin
tonybrant30-Oct-10 21:00
Membertonybrant30-Oct-10 21:00 
GeneralRe: how to invoke the java web service in a XNA game studio. Pin
Bikash Shaw3-Nov-10 4:39
MemberBikash Shaw3-Nov-10 4:39 
GeneralMy vote of 5 Pin
D V L20-Aug-10 13:18
professionalD V L20-Aug-10 13:18 
GeneralMy vote of 5 Pin
liminjun8831-Jul-10 21:25
Memberliminjun8831-Jul-10 21:25 
GeneralThanks Pin
Member 245270418-Apr-10 8:18
MemberMember 245270418-Apr-10 8:18 
GeneralSecured Interoperable web service Pin
vvasudev7-Apr-10 5:53
Membervvasudev7-Apr-10 5:53 
GeneralRe: Secured Interoperable web service Pin
Bikash Shaw30-Oct-10 0:25
MemberBikash Shaw30-Oct-10 0:25 
GeneralThank You, A Question Pin
Miles Rosenberg28-Oct-09 15:25
MemberMiles Rosenberg28-Oct-09 15:25 
GeneralThanks and questions Pin
jcduce17-Jun-09 5:21
Memberjcduce17-Jun-09 5:21 
GeneralGreat Job Pin
Brij7-Jan-09 2:31
mentorBrij7-Jan-09 2:31 
GeneralThis is Perfect..Good Job !! Pin
Abhijit Jana7-Jan-09 2:27
professionalAbhijit Jana7-Jan-09 2:27 
GeneralGot my 5 Pin
canozurdo7-Jan-09 1:20
Membercanozurdo7-Jan-09 1:20 
GeneralRe: Got my 5 Pin
Abhijit Jana7-Jan-09 2:38
professionalAbhijit Jana7-Jan-09 2:38 
GeneralRe: Got my 5 Pin
Bikash Shaw7-Jan-09 19:57
MemberBikash Shaw7-Jan-09 19:57 

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.