Link to home
Start Free TrialLog in
Avatar of scm0sml
scm0sml

asked on

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.
SOLUTION
Avatar of Anurag Thakur
Anurag Thakur
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of Kevin Cross
Kevin Cross
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of scm0sml
scm0sml

ASKER

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.
Avatar of scm0sml

ASKER

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.
Avatar of scm0sml

ASKER

the examples on here seem to be particularly complicated as such.

Can this not be done with just a few lines of code?
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
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.
Avatar of scm0sml

ASKER

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?
Avatar of scm0sml

ASKER

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.
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
Avatar of scm0sml

ASKER

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.
    }
}
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 "".
Avatar of scm0sml

ASKER

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);?
Avatar of scm0sml

ASKER

if so i am still getting nothing displayed?
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.
Try commenting out this line also:

//out.println("Connection: Close");
Avatar of scm0sml

ASKER

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:
https://www.experts-exchange.com/questions/23911088/manually-passing-function-name-and-params-to-a-webservice-in-browser.html?anchorAnswerId=22977198#a22977198
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.
Avatar of scm0sml

ASKER

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?
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.
Avatar of scm0sml

ASKER

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?
Avatar of scm0sml

ASKER

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?
Avatar of scm0sml

ASKER

have just broken into the catch and the exception is SocketException "Connection Reset"

Mean anything?
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.
Avatar of scm0sml

ASKER

i have yeah.....

cany believe the problems im having with this :(

have u had my example code working?
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.
Avatar of scm0sml

ASKER

damn. i meant java!!!

im not finding much for calling a .net 2 webservice from java though
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.
Avatar of scm0sml

ASKER

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?
Avatar of scm0sml

ASKER

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
?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
Avatar of scm0sml

ASKER

I have allocated the points based on the amount of help each person has given me.