Solved

calling a vb.net webservice from java

Posted on 2008-10-27
34
1,485 Views
Last Modified: 2012-05-05
i am a .net developer but have been asked to investigate calling a .net 2 webservice from javascript.

Say I have a webservice Service.asmx that has one function:
Public Function HelloWorld(ByVal name As String) As String
        Return "Hello " & name
    End Function

could someone provide me with some simple steps required to call it from java?

this would be much appreciated.
0
Comment
Question by:scm0sml
  • 18
  • 10
  • 3
  • +1
34 Comments
 
LVL 26

Assisted Solution

by:Anurag Thakur
Anurag Thakur earned 150 total points
Comment Utility
have a look at the following sample from code project
http://www.codeproject.com/KB/XML/WSfromJava.aspx

Consume .NET web-service in Java.
http://vaibhavgaikwad.wordpress.com/2006/11/13/consume-net-web-service-in-java/
0
 
LVL 59

Accepted Solution

by:
Kevin Cross earned 300 total points
Comment Utility
I had a glance at the links and didn't see this in the content, but sorry for any duplication.  You can also utilize these (using http://localhost/yourwebservice.asmx?wsdl as source of WSDL file):

Eclipse WTP (AXIS):
http://www.eclipse.org/webtools/jst/components/ws/1.5/tutorials/WebServiceClient/WebServiceClient.html

NetBeans:
http://www.netbeans.org/kb/60/websvc/client.html#creatingtheclient

Hope that helps.
0
 

Author Comment

by:scm0sml
Comment Utility
OK Just to state what i have at the moment.

I have a simple vb.net webservice
http://localhost:2458/SimpleService/Service.asmx

with the function:
<WebMethod()> _
    Public Function HelloWorld(ByVal name As String) As String
        Return "Hello " & name & "'s World!"
    End Function

I then have this very simple java class:
import java.io.*;
import java.net.*;

class HelloWorldApp
{
    public static void main(String[] args) {
                    
            System.out.println("Hello World!"); // Display the string.
    }
}

Basically I want to make a call to the webservice passing it a name, this can be hardcoded for now.

And then display the returned string.

So sending Simon for e.g would give us Hello Simon's World! as a reply to display.
0
 

Author Comment

by:scm0sml
Comment Utility
obviously i am just trying to get the java call to the webservice working and il then go on and get the real functionality im after working.
0
 

Author Comment

by:scm0sml
Comment Utility
the examples on here seem to be particularly complicated as such.

Can this not be done with just a few lines of code?
0
 
LVL 26

Expert Comment

by:Anurag Thakur
Comment Utility
its a bit complicated as you will not find person expert in both the languages C# and Java
i got the samples from the internet and i have posted it and hoped they help you
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
I agree.  Were the links we posted in first two comments not sufficient?

If you have Eclispe OR NetBeans you can use what I showed and it will create the proxy/stub classes for you in the same manner Visual Studio will create them for you if you add a web reference to a web service from your project.  Then as in Visual Studio, you can reference the web method like you would the method of any other class you can instantiate.

If you don't want to use that, you can use the javax.xml.soap API or just simply create a string that exactly matches the XML SOAP envelope shown as example when you hit your web service (ASMX) through Internet Explorer.
0
 

Author Comment

by:scm0sml
Comment Utility
the code hangs at this point:
String response = s.sendRequest();

i dont get an error or anything and am not used to debuggin in java. any ideas?
0
 

Author Comment

by:scm0sml
Comment Utility
ive tried:
try
            {
                  String response = s.sendRequest();
                  System.out.println(response); // Display the string.
            }
            catch(Exception ex)
            {
                  String response = "Error: cannot communicate.";
                  System.out.println(response); // Display the string.
            }

but still get nothing printed.
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
What is the rest of the code?

I apologize for the delay in response by the way.  But need to know where s is coming from here as I think you are indicating that you are catching exceptions here but you get nothing printed at all either from try block or catch block.

Depending on the IDE you are using to code this, you can usually click on the left hand side to set breakpoints in code and then you can launch application in debug mode and it will stop at your breakpoint.  You can then see if response ever gets set to a value, etc.

Regards,
Kevin
0
 

Author Comment

by:scm0sml
Comment Utility
import java.applet.Applet;
import java.awt.*;
import java.net.*;
import java.util.*;
import java.io.*;

class SoapRequestBuilder
{
      String Server = "";
      String WebServicePath = "";
      String SoapAction = "";
      String MethodName = "";
      String XmlNamespace = "";
      private Vector ParamNames = new Vector();
      private Vector ParamData = new Vector();

      public void AddParameter(String Name, String Data)
      {
            ParamNames.addElement((Object)Name);
            ParamData.addElement((Object)Data);
      }

      public String sendRequest()
      {
            String retval = "";
            Socket socket = null;
            try
            {
                  socket = new Socket(Server, 80);
            }
            catch (Exception ex1)
            {
                  return ("Error: " + ex1.getMessage());
            }

            try
            {
                  OutputStream os = socket.getOutputStream();
                  boolean autoflush = true;
                  PrintWriter out = new PrintWriter(socket.getOutputStream(), autoflush);
                  BufferedReader in = new BufferedReader(new InputStreamReader(socket.
                        getInputStream()));

                  int length = 295 + (MethodName.length() * 2) + XmlNamespace.length();
                  for (int t = 0; t < ParamNames.size(); t++)
                  {
                        String name = (String)ParamNames.elementAt(t);
                        String data = (String)ParamData.elementAt(t);
                        length += name.length();
                        length += data.length();
                  }

                  // send an HTTP request to the web service
                  out.println("POST " + WebServicePath + " HTTP/1.1");
                  out.println("Host: localhost:80");
                  out.println("Content-Type: text/xml; charset=utf-8");
                  out.println("Content-Length: " + String.valueOf(length));
                  out.println("SOAPAction: \"" + SoapAction + "\"");
                  out.println("Connection: Close");
                  out.println();

                  out.println("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                  out.println("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
                  out.println("<soap:Body>");
                  out.println("<" + MethodName + " xmlns=\"" + XmlNamespace + "\">");
                  //Parameters passed to the method are added here
                  for (int t = 0; t < ParamNames.size(); t++)
                  {
                        String name = (String)ParamNames.elementAt(t);
                        String data = (String)ParamData.elementAt(t);
                        out.println("<" + name + ">" + data + "</" + name + ">");
                  }
                  out.println("</" + MethodName + ">");
                  out.println("</soap:Body>");
                  out.println("</soap:Envelope>");
                  out.println();

                  // Read the response from the server ... times out if the response takes
                  // more than 3 seconds
                  String inputLine;
                  StringBuffer sb = new StringBuffer(1000);

                  int wait_seconds = 3;
                  boolean timeout = false;
                  long m = System.currentTimeMillis();
                  while ((inputLine = in.readLine()) != null && !timeout)
                  {
                        sb.append(inputLine + "\n");
                        if ((System.currentTimeMillis() - m) > (1000 * wait_seconds)) timeout = true;
                  }
                  in.close();

                  // The StringBuffer sb now contains the complete result from the
                  // webservice in XML format.  You can parse this XML if you want to
                  // get more complicated results than a single value.

                  if (!timeout)
                  {
                        String returnparam = MethodName + "Result";
                        int start = sb.toString().indexOf("<" + returnparam + ">") +
                              returnparam.length() + 2;
                        int end = sb.toString().indexOf("</" + returnparam + ">");

                        //Extract a singe return parameter
                        retval = sb.toString().substring(start, end);
                  }
                  else
                  {
                        retval = "Error: response timed out.";
                  }

                  socket.close();
            }
            catch (Exception ex)
            {
                  return ("Error: cannot communicate.");
            }

            return retval;
      }
}


class HelloWorldApp
{
    public static void main(String[] args) {

      SoapRequestBuilder s = new SoapRequestBuilder();
            s.Server = "localhost"; // server ip address or name
      
            //s.Server = "127.0.0.1"; // server ip address or name
            s.MethodName = "HelloWorld";
            s.XmlNamespace = "http://tempuri.org/";
            s.WebServicePath = "/SimpleService/Service.asmx";
            
            s.SoapAction = s.XmlNamespace + s.MethodName;
            s.AddParameter("name", "David");
            //s.AddParameter("two", "Hobbs");            
            try
            {
                  String response = s.sendRequest();
                  System.out.println(response); // Display the string.
            }
            catch(Exception ex)
            {
                  String response = "Error: cannot communicate.";
                  System.out.println(response); // Display the string.
            }
//String response = "yo yo";

            
            //System.out.println("Hello World!"); // Display the string.
    }
}
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
if (!timeout)
                  {
                        String returnparam = MethodName + "Result";
                        int start = sb.toString().indexOf("<" + returnparam + ">") +
                              returnparam.length() + 2;
                        int end = sb.toString().indexOf("</" + returnparam + ">");

                        //Extract a singe return parameter
                        retval = sb.toString().substring(start, end);
                  }

Try setting retval to the entire string here.  You are not seeing anything as there is probably not an Exception thrown in the Java sense, but your XML response could not contain element you are looking for.  retval starts out as "" and unless certain conditions are met stays that way; therefore, the reason you are not seeing any of your error traces is that you are flowing through part of code without Exception being thrown most likely but the value of retval is "".
0
 

Author Comment

by:scm0sml
Comment Utility
As far as I can see you have made no code change there, just pointing out wqhere to make one yes?

do you mean:
retval = sb.toString();//.substring(start, end);?
0
 

Author Comment

by:scm0sml
Comment Utility
if so i am still getting nothing displayed?
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
Correct, I apologize.  I was trying to make it easier for you to find what I was talking about.

I would put breakpoints on this then and ensure that the XML string you are building to send to web service looks OK and what is happening with the response as it seems like you are getting back "" as response or it is being lost in translation to the sb object.

If you open web browser on the machine hosting the web service and type in the same parameters you are using here, does the response come back as expected?  That would be a good double check.  I have found sometimes I have chased code only to find that users found a way to do the impossible in the data like have a bill of material for a part with no quantity per assembly so web service would get an error parsing value and not return XML if I didn't write code to catch that exception.

Anyway, you can also confirm my theory by setting retval to some literal string like "<greetings>Hello World!</greetings>" and see if works then.  You can test out all the other pieces of code and then know for sure to focus on debugging the portion of code sending/receiving the XML with web service.
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
Try commenting out this line also:

//out.println("Connection: Close");
0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 

Author Comment

by:scm0sml
Comment Utility
not having much luck at the mo.

two things, what do u use to debug and break into your java code? im running thru the command prompt at the mo.

also can u advise on this thread as i posted it based on your suggestion above:
http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_23911088.html#a22977198
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
I use NetBeans or Eclipse and they both have debugger like Visual Studio where you can set breakpoints in code and run in debug mode which will stop code at breakpoint and allow you to step into, through, etc.
0
 

Author Comment

by:scm0sml
Comment Utility
ok have downloaded netbeans.

stupid question!!

before i was just doing  java HelloWorldApp in the command prompt.

how would i break into this code using netbeans.

do i need a form with a button on or something?
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
No.  

Don't need to change any code logic, just open up source (.java) file for HelloWorldApp and put breakpoints in code -- easiest way is to click in the thin column on the left which is slightly shaded in the code editor pane.

If you then right click on file, you can use the debug HelloWorldApp.java option that appears and it will simply run the program as a command line application as it was before.  You will just have a command pane right in NetBeans instead of having to use a windows command prompt.
0
 

Author Comment

by:scm0sml
Comment Utility
right ive used some debuggin lines to find that we get this:
System.out.println("Got here...1.3");
                  while ((inputLine = in.readLine()) != null && !timeout)
                  {
                        System.out.println("Got here...1.4");
                        sb.append(inputLine + "\n");
                        if ((System.currentTimeMillis() - m) > (1000 * wait_seconds)) timeout = true;
                  }
                  System.out.println("Got here...1.5");


upto System.out.println("Got here...1.3"); gets printed out but then it hangs so looks like it isnt even getting into that loop as i never get the 1.4 line printed?

anything stand out to u?
0
 

Author Comment

by:scm0sml
Comment Utility
could it been there is a problem with:
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));??

I have broken into the code and am looking through the socket properties...it says its connected?

is there any information i can give you to help debug what is going on?
0
 

Author Comment

by:scm0sml
Comment Utility
have just broken into the catch and the exception is SocketException "Connection Reset"

Mean anything?
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
Did you comment out this line?

//out.println("Connection: Close");

Connection Reset is usually when the server receives the request and processes but the socket thinks the connection is closed.
0
 

Author Comment

by:scm0sml
Comment Utility
i have yeah.....

cany believe the problems im having with this :(

have u had my example code working?
0
 
LVL 51

Expert Comment

by:tedbilly
Comment Utility
I'm somewhat confused by this question because you've mentioned Java and JavaScript in the question.  Similiar names, different implementations. Which do you want to use?

If you search the web using 'Consume web service Java' or 'Consume web service JavaScript' you will get LOTS of hits.
0
 

Author Comment

by:scm0sml
Comment Utility
damn. i meant java!!!

im not finding much for calling a .net 2 webservice from java though
0
 
LVL 51

Expert Comment

by:tedbilly
Comment Utility
This looks like a good sample:
http://www.codeproject.com/KB/java/edujini_webservice_java.aspx

PS: I know this is possible because I did it about 7 years ago.  I don't have the code because it was with a previous employer.
0
 

Author Comment

by:scm0sml
Comment Utility
Right I have gone right back to the link given to me at the beginning of this thread, the link:
http://www.codeproject.com/KB/XML/WSfromJava.aspx

I am now trying to use this .net webservice code but am getting the same hanging problem as before.

I would imageine this code works normally so there is either some difference in consuming the 2005 webservice or there is some issue with my machine security or something.

Any ideas?
0
 

Author Comment

by:scm0sml
Comment Utility
FINALLY!!!!!!!!!!!!!

This is the address in the browser of my url when the service is running:
http://localhost:2458/SimpleService/Service.asmx

Changed:
socket = new Socket(Server, 80);
to
socket = new Socket(Server, 2458);

It worked......what a thread :(

How would I handle this when I want to put my code live, will it always have the same port
?
0
 
LVL 51

Assisted Solution

by:tedbilly
tedbilly earned 50 total points
Comment Utility
Assuming you configure the live web service the same way yes it should work.
0
 
LVL 59

Expert Comment

by:Kevin Cross
Comment Utility
Using Visual Studio, the embeded web server for testing uses dynamic ports so the port would change everytime you close down the server and relaunch your program through view in browser in VS.  When you deploy to production, you will have to configure the port you and ip address you want the service to run on.  It will be up to you if it is:

http://www.yourdomainname.com/SimpleService/Service.asmx
or
http://www.yourdomainname.com:2458/SimpleService/Service.asmx
0
 

Author Closing Comment

by:scm0sml
Comment Utility
I have allocated the points based on the amount of help each person has given me.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This theoretical tutorial explains exceptions, reasons for exceptions, different categories of exception and exception hierarchy.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now