calling a vb.net webservice from java

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.
scm0smlAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Anurag ThakurTechnical ManagerCommented:
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
Kevin CrossChief Technology OfficerCommented:
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
scm0smlAuthor Commented:
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
Cloud Class® Course: Microsoft Office 2010

This course will introduce you to the interfaces and features of Microsoft Office 2010 Word, Excel, PowerPoint, Outlook, and Access. You will learn about the features that are shared between all products in the Office suite, as well as the new features that are product specific.

scm0smlAuthor Commented:
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
scm0smlAuthor Commented:
the examples on here seem to be particularly complicated as such.

Can this not be done with just a few lines of code?
0
Anurag ThakurTechnical ManagerCommented:
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
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
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
scm0smlAuthor Commented:
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
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
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
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
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
scm0smlAuthor Commented:
if so i am still getting nothing displayed?
0
Kevin CrossChief Technology OfficerCommented:
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
Kevin CrossChief Technology OfficerCommented:
Try commenting out this line also:

//out.println("Connection: Close");
0
scm0smlAuthor Commented:
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
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
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
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
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
scm0smlAuthor Commented:
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
scm0smlAuthor Commented:
have just broken into the catch and the exception is SocketException "Connection Reset"

Mean anything?
0
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
i have yeah.....

cany believe the problems im having with this :(

have u had my example code working?
0
Ted BouskillSenior Software DeveloperCommented:
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
scm0smlAuthor Commented:
damn. i meant java!!!

im not finding much for calling a .net 2 webservice from java though
0
Ted BouskillSenior Software DeveloperCommented:
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
scm0smlAuthor Commented:
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
scm0smlAuthor Commented:
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
Ted BouskillSenior Software DeveloperCommented:
Assuming you configure the live web service the same way yes it should work.
0
Kevin CrossChief Technology OfficerCommented:
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
scm0smlAuthor Commented:
I have allocated the points based on the amount of help each person has given me.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.