Springs RestTemplate doesn't find the right MessageConverter when reciving data from the IMDB api - web-services

first I have to say, that I am pretty new to Springs RestTemplate.
I am trying to receive data from the imdb-api. (For example http://imdbapi.org/?title=Avatar&type=xml) Therefore I am using Springs RestTemplate.
But:
the webservice returns the data as application/octet-stream (even I declared that I want it as xml (when I browse the site with my browser I get the data as text/xml))
RestTemplate doesn't find my declared ByteArrayMessageConverter (to convert application/octet-stream)
I realy don't know where my mistakes are.
Here is the code to initialise the restTemplate:
public void onInit() {
_log.debug("Setting up the Spring Resttemplate");
_restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new SourceHttpMessageConverter<Source>());
list.add(new ByteArrayHttpMessageConverter());
_restTemplate.setMessageConverters(list);
_log.debug("Setting up the HTTP Headers for Restrequest");
List<MediaType> acceptableMediaTypes = new ArrayList<MediaType>();
_log.trace("allow {}", MediaType.APPLICATION_XML_VALUE);
acceptableMediaTypes.add(MediaType.APPLICATION_XML);
_log.trace("allow {}", MediaType.TEXT_HTML_VALUE);
acceptableMediaTypes.add(MediaType.TEXT_XML);
_log.trace("set accepted charset to uft-8");
List<Charset> acceptableCharsets = new ArrayList<Charset>();
acceptableCharsets.add(Charset.forName("utf-8"));
_httpHeaders = new HttpHeaders();
_httpHeaders.set("User-Agent", "something"); //only a user-agent, because the api returns a 403 if it is not set
_httpHeaders.setAcceptCharset(acceptableCharsets);
_httpHeaders.setAccept(acceptableMediaTypes);
}
Here is the code with the call:
_log.info("connect to Imdb-Webservice {}", _imbdWebserviceBaseUrl);
Map<String, Object> uriVariables = new HashMap<String, Object>();
uriVariables.put("title", pTitle);
ResponseEntity<Source> response = _restTemplate.exchange(_imbdWebserviceBaseUrl, HttpMethod.GET, new HttpEntity<String>(_httpHeaders), Source.class, uriVariables);
_imbdWebserviceBaseUrl is set to http://imdbapi.org/?title={title}&type=xml
Then I am getting this error message:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [interface javax.xml.transform.Source] and content type [application/octet-stream]
at org.springframework.web.client.HttpMessageConverterExtractor.extractData(HttpMessageConverterExtractor.java:107)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:687)
at org.springframework.web.client.RestTemplate$ResponseEntityResponseExtractor.extractData(RestTemplate.java:673)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:491)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:454)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:401)
at my.domain.projectname.integrationimpl.WebserviceHelper.getXml(WebserviceHelper.java:131)
Thanks for your help

the web service returns the data as application/octet-stream (even I declared that I want it as xml (when I browse the site with my browser I get the data as text/xml))
As far as I can see this rest service is not giving back the correct Content-Type (text/xml or similar). If your browser renders it correctly that's probably Chrome or Firefox, but IE will just show you html-ish kind of output.
RestTemplate doesn't find my declared ByteArrayMessageConverter (to convert application/octet-stream)
Well you are asking for a Source as far as I can see:
ResponseEntity<Source> response = _restTemplate.exchange(_imbdWebserviceBaseUrl, HttpMethod.GET, new HttpEntity<String>(_httpHeaders), Source.class, uriVariables);
The MessageConverters themselves have a method that determines if this converter is applicable, for ByteArrayHttpMessageConverter this is:
#Override
public boolean supports(Class<?> clazz) {
return byte[].class.equals(clazz);
}
Since you are asking for a Source.class it wont use this converter.

Related

Epicor ERP can you call an Epicor Function within a Customization

Epicor ERP 10.2.500 has been recently released with the addition of Epicor Functions. They can be called from within Method and Data Directives.
Do anybody has been able to do so with a Form Customization within Epicor?
This is possible via a REST call to your function API. In this case, I had a function that sent an email from some inputs.
private void epiButtonC1_Click(object sender, System.EventArgs args)
{
//API Key is included in the query param in this example.
var request = (HttpWebRequest)WebRequest.Create("https://{appserver}/{EpicorInstance}/api/v2/efx/{CompanyID}/{LibraryID}/{functionName}/?api-key={yourAPIKey}");
request.Method = "POST";
//All REST v2 requests also sent with authentication method (Token, Basic)
//This should be Base64 encoded
string username = "userName";
string password = "passWord";
string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
//Add body to correspond to request signature
request.ContentType = "application/json";
using(var writer = new StreamWriter(request.GetRequestStream()))
 {
    var values = new Dictionary<string, string>;
      {
        {"toEmailAddress", "someEmail#email.com"},
        {"fromEmailAddress","someOtherEmail#email.com"}, 
        {"body","This is the body"},   
{"subject","Hello from Client Code!"}
    };
    string json = JsonConvert.SerializeObject(values);
    writer.Write(json);
}
using (var response = request.GetResponse()) 
using (var reader = new StreamReader(response.GetResponseStream()))
{
  var result = reader.ReadToEnd();
  epiTextBoxC1.Text = result.ToString();
}
}
Haven't done it myself personally, but looking into the first post release notes about it here leads me to believe there is no out of the box solution, yet in this version/initial release.
However I'm sure you could do a HTTP request from within the Epicor customization if you have the REST API enabled in your environment.
If you create your own dll that calls the EpicorFunction you can use it within the customization. Still looking for a way to call them directly.
REST endpoint is the recommended way to perform the function call as pointed out by a-moreng.
If for some reason you cannot use this, you can use a passthrough method to any server-side BO via a customization Adapter. For instance, create an updatable BAQ which you can call from a customization using the DynamicQueryAdapter.
Pick an arbitrary table and field to save the BAQ.
Create three string parameters to store the Function library name, the function name, and a delimited list of parameters.
On the GetList method, create a Base Processing Directive.
Split your delimited parameter list and convert them to the appropriate datatypes.
Use the resulting variables to call your function.
If desired, you can pass return variables into the ttResults of the BAQ

Web Service Class of AS in Flex 4

I am trying to receive data from the Web Service and I am getting the Data from Web Service back but it is form of [object Object]. Can anybody help me on this.
Below is the code for my web service:
public class WebServiceAccess
{
private var webService:WebService;
private var serviceOperation:AbstractOperation;
private var myValueObjects:ValueObjects;
private var method:String;
[Bindable]
public var employeeData:ArrayCollection;
[Bindable]
public var employees:ArrayCollection;
public function WebServiceAccess(url:String, method:String)
{
webService = new WebService();
this.method = method;
webService.loadWSDL(url);
webService.addEventListener(LoadEvent.LOAD, ServiceRequest);
}
public function ServiceRequest():void
{
serviceOperation = webService.getOperation(method);
serviceOperation.addEventListener(FaultEvent.FAULT, DisplayError);
serviceOperation.addEventListener(ResultEvent.RESULT, DisplayResult);
serviceOperation.send();
}
public function DisplayError(evt:FaultEvent):void
{
Alert.show(evt.fault.toString());
}
public function DisplayResult(evt:ResultEvent):void
{
employeeData = evt.result as ArrayCollection;
Alert.show(employeeData.toString());
}
}
First of all, evt.result is not an ArrayCollection, it is an Object (unless your SOAP service/WSDL are completely screwed up/malformed XML).
Second, you can't just display an Array or ArrayCollection (or generic Object, even) as a String (even though the .toString() method always seems to imply that) anyway, you have to parse the data to get what you want from it.
Now, the WebService class is nice in that it automatically parses the XML file that a SOAP service returns into a single usable Object. So that is actually the hard part.
What you need to do is call various properties of the object to get the data you need.
So if the XML return (look at your WSDL to see what the return should be, I also highly suggest soapUI) is this:
<employee name="Josh">
<start date="89384938984"/>
<photo url="photo.jpg"/>
</employee>
And you wanted to display "Josh" and the photo, you would do this.
var name:String = e.result.employee.name;
var url:String = e.result.employee.photo.url;
It does get more complicated. If the WSDL allows for multiple nodes with the same name at the same level, it does return an ArrayCollection. Then you have to loop through the array and find the exact item you need.
Just remember: The WSDL is god. Period. If it says there can be multiple "employee" nodes, you have to code accordingly, even if you don't see more than one in your tests. The issue is that there always could be multiple nodes.

Add SOAP header object using pure JAX-WS

I'm trying to implement simple web service client for PayPal Express Checkout API using JAX WS. PayPal Express Checkout API provides WSDL file, from which I was able to generate Java classes using CXF's wsdl2java utility.
From authentication reasons, it demands adding SOAP Header to each request. This header is quite simple and should look like here:
https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_api_ECSOAPAPIBasics#id09C3I0CF0O6
Generated from WSDL classes include ebay.apis.eblbasecomponents.CustomSecurityHeaderType class which represents header which I need to add to each request.
So the question is: how can I add manually created instance of CustomSecurityHeaderType class to SOAP request's header taking into account following conditions:
I'm not very eager to use classes from com.sun.* package as mentioned in answer here: JAX-WS - Adding SOAP Headers (mainly because of possible portability issues between different JDK's)
I don't want to manually marshal that object into nested javax.xml.soap.SOAPElement instances as mentioned in answer here:
How do I add a SOAP Header using Java JAX-WS
So, it looks like I've found possible answer while combining JAX-WS & JAXB related answers from SO (I would really appreciate if somebody experienced in these technologies can check whether following is correct):
The obvious thing for me is to add SOAP message handler and alter header of SOAPMessage instance in it:
import javax.xml.ws.Binding;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.handler.Handler;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.soap.SOAPHeader;
import ebay.api.paypalapi.ObjectFactory; // class generated by wsdl2java
// following class is generated by wsdl2java utility Service class
final PayPalAPIInterfaceService payPalService = new PayPalAPIInterfaceService();
final PayPalAPIAAInterface expressCheckoutPort = payPalService.getPayPalAPIAA();
final Binding binding = ((BindingProvider) expressCheckoutPort).getBinding();
List<Handler> handlersList = new ArrayList<Handler>();
// now, adding instance of Handler to handlersList which should do our job:
// creating header instance
final CustomSecurityHeaderType headerObj = new CustomSecurityHeaderType();
final UserIdPasswordType credentials = new UserIdPasswordType();
credentials.setUsername("username");
credentials.setPassword("password");
credentials.setSignature("signature");
headerObj.setCredentials(credentials);
// bookmark #1 - please read explanation after code
final ObjectFactory objectFactory = new ObjectFactory();
// creating JAXBElement from headerObj
final JAXBElement<CustomSecurityHeaderType> requesterCredentials = objectFactory.createRequesterCredentials(headerObj);
handlersList.add(new SOAPHandler<SOAPMessageContext>() {
#Override
public boolean handleMessage(final SOAPMessageContext context) {
try {
// checking whether handled message is outbound one as per Martin Strauss answer
final Boolean outbound = (Boolean) context.get("javax.xml.ws.handler.message.outbound");
if (outbound != null && outbound) {
// obtaining marshaller which should marshal instance to xml
final Marshaller marshaller = JAXBContext.newInstance(CustomSecurityHeaderType.class).createMarshaller();
// adding header because otherwise it's null
final SOAPHeader soapHeader = context.getMessage().getSOAPPart().getEnvelope().addHeader();
// marshalling instance (appending) to SOAP header's xml node
marshaller.marshal(requesterCredentials, soapHeader);
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
return true;
}
// ... default implementations of other methods go here
});
// as per Jean-Bernard Pellerin's comment setting handlerChain list here, after all handlers were added to list
binding.setHandlerChain(handlersList);
Explanation of bookmark #1:
one should marshal not the header object itself, but JAXBElement representing that object, because otherwise one will get an exception. One should use one of ObjectFactory classes which are generated from WSDL for creating needed JAXBElement instances from original objects.
(Thanks #skaffman for answer: No #XmlRootElement generated by JAXB )
One should also refer to Martin Straus answer which extends this one
This solution works great, but there's a catch. It generates this error when the inbound message is processed:
dic 19, 2012 7:00:55 PM com.sun.xml.messaging.saaj.soap.impl.EnvelopeImpl addHeader
SEVERE: SAAJ0120: no se puede agregar una cabecera si ya hay una
Exception in thread "main" javax.xml.ws.WebServiceException: java.lang.RuntimeException: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present.
at com.sun.xml.ws.handler.ClientSOAPHandlerTube.callHandlersOnResponse(ClientSOAPHandlerTube.java:167)
at com.sun.xml.ws.handler.HandlerTube.processResponse(HandlerTube.java:174)
at com.sun.xml.ws.api.pipe.Fiber.__doRun(Fiber.java:1074)
at com.sun.xml.ws.api.pipe.Fiber._doRun(Fiber.java:979)
at com.sun.xml.ws.api.pipe.Fiber.doRun(Fiber.java:950)
at com.sun.xml.ws.api.pipe.Fiber.runSync(Fiber.java:825)
at com.sun.xml.ws.client.Stub.process(Stub.java:443)
at com.sun.xml.ws.client.sei.SEIStub.doProcess(SEIStub.java:174)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
at com.sun.xml.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:102)
at com.sun.xml.ws.client.sei.SEIStub.invoke(SEIStub.java:154)
at $Proxy38.wsRdyCrearTicketDA(Unknown Source)
at ar.com.fit.fides.remedy.api.ws.ServicioCreacionTickets.crearTicket(ServicioCreacionTickets.java:55)
at ar.com.fit.fides.remedy.api.ws.ConectorRemedyWS.crearTicket(ConectorRemedyWS.java:43)
at ar.com.fit.fides.remedy.api.ws.ConectorRemedyWS.main(ConectorRemedyWS.java:90)
Caused by: java.lang.RuntimeException: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present.
at ar.com.fit.fides.remedy.api.ws.AuthenticationHandler.handleMessage(AuthenticationHandler.java:50)
at ar.com.fit.fides.remedy.api.ws.AuthenticationHandler.handleMessage(AuthenticationHandler.java:23)
at com.sun.xml.ws.handler.HandlerProcessor.callHandleMessageReverse(HandlerProcessor.java:341)
at com.sun.xml.ws.handler.HandlerProcessor.callHandlersResponse(HandlerProcessor.java:214)
at com.sun.xml.ws.handler.ClientSOAPHandlerTube.callHandlersOnResponse(ClientSOAPHandlerTube.java:161)
... 14 more
Caused by: com.sun.xml.messaging.saaj.SOAPExceptionImpl: Can't add a header when one is already present.
at com.sun.xml.messaging.saaj.soap.impl.EnvelopeImpl.addHeader(EnvelopeImpl.java:128)
at com.sun.xml.messaging.saaj.soap.impl.EnvelopeImpl.addHeader(EnvelopeImpl.java:108)
at ar.com.fit.fides.remedy.api.ws.AuthenticationHandler.handleMessage(AuthenticationHandler.java:45)
So, the solution is to check whether the message being handled if the outbound message, like this:
public boolean handleMessage(SOAPMessageContext context) {
try {
Boolean outbound = (Boolean) context.get("javax.xml.ws.handler.message.outbound");
if (outbound != null && outbound) {
// obtaining marshaller which should marshal instance to xml
final Marshaller marshaller = JAXBContext.newInstance(AuthenticationInfo.class).createMarshaller();
// adding header because otherwise it's null
final SOAPHeader soapHeader = context.getMessage().getSOAPPart().getEnvelope().addHeader();
// marshalling instance (appending) to SOAP header's xml node
marshaller.marshal(info, soapHeader);
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
return true;
}
I created a web service exposing method with params user and password as header like this:
#WebService(serviceName="authentication")
public class WSAuthentication {
String name = null;
String password = null;
public WSAuthentication() {
super();
}
public WSAuthentication(String name, String password) {
this.name = name;
this.password = password;
}
private static String getData(WSAuthentication sec) {
System.out.println("********************* AUTHENTICATION ********************" + "\n" +
"**********USER: " + sec.name + "\n" +
"******PASSWORD: " + sec.password + "\n" +
"******************************** AUTHENTICATION ****************************");
return sec.name + " -- " + sec.password;
}
#WebMethod(operationName="security", action="authenticate")
#WebResult(name="answer")
public String security(#WebParam(header=true, mode=Mode.IN, name="user") String user, #WebParam(header=true, mode=Mode.IN, name="password") String password) {
WSAuthentication secure = new WSAuthentication(user, password);
return getData(secure);
}
}
Try compiling it and testing generated from WSDL class. I hope this helps.
I found this answer:
JAX-WS - Adding SOAP Headers
Basically you add -XadditionalHeaders to the compiler options and objects in the headers also appear in your generated code as parameters of the method.
If you are using maven, and the jaxws-maven-plugin all you have to do is add the xadditionalHeaders flag to true and the client will be generated with the methods that have the headers as input.
https://jax-ws-commons.java.net/jaxws-maven-plugin/wsimport-mojo.html#xadditionalHeaders

Using Apache HttpComponents for http requests with NTLM authentication

Quick background.
CFHTTP doesn't support Windows NTLM/Authenticate authentication, only basic authentication. I need to make http requests that will have to authenticate against NTLM, so I've ended up rolling my own version of CFHTTP.
I found Terry Ryan's article that uses the apache httpclient version 3.1 to perform digest authentication and have built upon that using version 4.1.2 instead which includes NTLM functionality.
I have a function that will perform a get request and then other functions to handle returning a structure that looks like the cfhttp result set. The changes I made are based on the authentication tutorial example.
public any function httpRequest(url,username,password,domain) {
var httpClient = createObject("java","org.apache.http.impl.client.DefaultHttpClient");
var authScope = createObject("java","org.apache.http.auth.AuthScope");
var httpCredentials = createObject("java","org.apache.http.auth.NTCredentials");
var httpGet = createObject("java","org.apache.http.client.methods.HttpGet");
var jURL = createObject("java", "java.net.URL").init(arguments.url);
var host = jURL.getHost();
var path = jURL.getPath();
var httpHostTarget = createObject("java","org.apache.http.HttpHost").init(host,80,"http");
var localContext = createObject("java","org.apache.http.protocol.BasicHttpContext");
var httpContent = {};
var response = '';
if (len(arguments.username) and len(arguments.password) gt 0){
httpCredentials.init(arguments.Username, arguments.password, cgi.remote_host,arguments.domain);
httpClient.getCredentialsProvider().setCredentials(authScope.ANY, httpCredentials);
}
if (!Len(path)) path = "/";
httpGet.init(path);
response = httpClient.execute(httpHostTarget, httpget, localContext);
httpContent = convertHttpClientResponseToCFHTTPFormat(response);
httpClient.getConnectionManager().shutdown();
return httpContent;
}
This was working fine until I altered the function to perform the authentication.
Unfortunately I'm now getting :
The execute method was not found.
Either there are no methods with the specified method name and argument types or the execute method is overloaded with argument types that ColdFusion cannot decipher reliably. ColdFusion found 2 methods that match the provided arguments. If this is a Java object and you verified that the method exists, use the javacast function to reduce ambiguity.
As far as I can tell there is only one matching execute() function in HttpClient for the object classes passed to it, so I'm a little confused. JavaCast doesn't allow you to cast to complex objects or super types, so that didn't work.
Can anyone suggest how I can get this to work? How can I reduce the ambiguity?
Looking at the error, it's getting confused between two execute methods that have the same number of parameters. Although I don't know why it is...
Anyway, I found a way around the error. It involves pulling the method you're after out of the class and invoking it directly. If ColdFusion was happier with casting Java objects life might be easier.
//response = httpClient.execute(httpHostTarget, httpget, localContext);
classes = [httpHostTarget.getClass(), CreateObject('java', 'org.apache.http.HttpRequest').getClass(), CreateObject('java', 'org.apache.http.protocol.HttpContext').getClass()];
method = httpClient.getClass().getMethod('execute', classes);
params = [httpHostTarget, httpget, localContext];
response = method.invoke(httpClient, params);
There may be another way of doing this (casting instead) but it's all I've got ;)
As a guess, could you be loading the wrong version of the .jars ? You don't seem to be using JavaLoader like Ryan did...

Classic Asp Web Service Problem

I'm trying to create a code to allow an existing classic asp program to use an asp.net web service. Updating from the classic asp is not an option, as I'm working in a big company and things are the way they are.
I've been browsing through a chunk of tutorials supposedly helping in this, but I haven't managed to get them to work yet. As a beginner I might've made some real obvious mistakes but I just don't know what.
First, the web service is located on an external server. The method "Greeting" needs a String parameter by which it determines which String is sent back. Inputting "g" to it procudes this xml:
<?xml version="1.0" encoding="utf-8" ?>
<string xmlns="http://server1/Logger_WebService/">Greetings and welcome!</string>
I assume the xpath for getting the contents is either "string/*" or "*"?
Next, my web service itself looks like this:
<WebMethod()> _
Public Function Greeting(ByVal stringel As String) As String
If stringel.ToLower = "g" Then
Return "Greetings and welcome!"
Else
Return "Bye then!"
End If
End Function
The web service works fine from a regular asp.net solution.
Now here's the problem, the classic asp code looks like this (4 different ways I've tried to get this to work, SOAP toolkit is installed on the web service server, all examples taken and modified from tutorials):
'******* USING GET METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting?g"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "GET",wsurl,false
xmlhttp.send
Dim rValue
'rValue=xmlhttp.responseXML.selectSingleNode("string") 'use XPATH as input argument
' or you can get response XML
rValue=xmlhttp.responseXML
Set xmlhttp=nothing
'------------------------------------------------------
'******* USING POST METHOD
Dim wsurl="http://server1/Logger_WebService/service.asmx/Greeting"
Dim xmlhttp
Set xmlhttp=Server.CreateObject("MSXML2.ServerXMLHTTP")
xmlhttp.open "POST",wsurl,false
xmlhttp.send "stringeli=g"
Dim rValue
rValue=xmlhttp.responseXML.selectSingleNode("string")
' or you can get response XML
' rValue=xmlhttp.responseXML
Set xmlhttp=nothing
'------------------------------------------------------
Response.Write consumeWebService()
Function consumeWebService()
Dim webServiceUrl, httpReq, node, myXmlDoc
webServiceUrl = "http://server1/Logger_WebService/service.asmx/Greeting?stringel=g"
Set httpReq = Server.CreateObject("MSXML2.ServerXMLHTTP")
httpReq.Open "GET", webServiceUrl, False
httpReq.Send
Set myXmlDoc =Server.CreateObject("MSXML.DOMDocument")
myXmlDoc.load(httpReq.responseBody)
Set httpReq = Nothing
Set node = myXmlDoc.documentElement.selectSingleNode("string/*")
consumeWebService = " " & node.text
End Function
'------------------------------------------------------
Response.Write(Helou())
Public Function Helou()
SET objSoapClient = Server.CreateObject("MSSOAP.SoapClient")
objSoapClient.ClientProperty("ServerHTTPRequest") = True
' needs to be updated with the url of your Web Service WSDL and is
' followed by the Web Service name
Call objSoapClient.mssoapinit("http://server1/Logger_WebService/service.asmx?WSDL", "Service")
' use the SOAP object to call the Web Method Required
Helou = objSoapClient.Greeting("g")
End Function
I seriously have no idea why nothing works, I've tried them every which way with loads of different settings etc. One possible issue is that the web service is located on a server which in ASP.Net required me to input this "[ServiceVariableName].Credentials = System.Net.CredentialCache.DefaultCredentials". I do this from within company network, and there are some security and authorization issues.
I only need to be able to send information anyhow, not receive, as the actual method I will be using is going to insert information into a database. But for now, just getting the Hello World thingie to work seems to provide enough challenge. :)
Thx for all the help. I'll try to check back on holiday hours to check and reply to the comments, I've undoubtedly left out needed information.
Please, talk as you would to an idiot, I'm new to this so chances are I can understand better that way. :)
You might consider writing a bit of .NET wrapper code to consume the web service. Then expose the .NET code as a COM object that the ASP can call directly. As you've seen, there is no tooling to help you in classic ASP, so consider using as much .NET as possible, for the tooling. Then, use COM to interoperate between the two.
A colleague finally got it working after putting a whole day into it. It was decided that it's easier by far to send information than it is to receive it. Since the eventual purpose of the web service is to write data to the DB and not get any message back, we attempted the thing by simply writing a file in the web service.
The following changes were needed:
First, in order to get it to work through the company networks, anonymous access had to be enabled in IIS.
The web service needed the following change in the web.config:
<webServices>
<protocols>
<add name="HttpGet"/>
</protocols>
</webServices>
And the web service code-behind was changed like so:
<WebMethod()> _
Public Function Greeting(ByVal stringel As String) As String
Dim kirj As StreamWriter
'kirj = File.CreateText("\\server1\MyDir\Logger_WebService\test.txt")
'if run locally, the line above would need to be used, otherwise the one below
kirj = File.CreateText("C:\Inetpub\serverroot\MyDir\Logger_WebService\test.txt")
kirj.WriteLine(stringel)
kirj.Close()
kirj.Dispose()
Return stringel
End Function
As we got the above to work, it was a simple matter of applying the same to the big web method that would parse and check the info and insert it into the database.
The classic asp code itself that needs to be added to the old page, which was the biggest problem, turned out to be relatively simple in the end.
function works()
message = "http://server1/mydir/logger_webservice/service.asmx/Greeting?" & _
"stringel=" & "it works"
Set objRequest = Server.createobject("MSXML2.XMLHTTP")
With objRequest
.open "GET", message, False
.setRequestHeader "Content-Type", "text/xml"
.send
End With
works = objRequest.responseText
end function
works()
Took about a week's worth of work to get this solved. :/ The hardest part was simply not ever knowing what was wrong at any one time.
You might be missing the SOAPAction header. Here's a working example:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class GreetingService : WebService
{
[WebMethod]
public string Greet(string name)
{
return string.Format("Hello {0}", name);
}
}
And the calling VBS script:
Dim SoapRequest
Set SoapRequest = CreateObject("MSXML2.XMLHTTP")
Dim myXML
Set myXML = CreateObject("MSXML.DOMDocument")
myXML.Async=False
SoapRequest.Open "POST", "http://localhost:4625/GreetingService.asmx", False
SoapRequest.setRequestHeader "Content-Type","text/xml;charset=utf-8"
SoapRequest.setRequestHeader "SOAPAction", """http://tempuri.org/Greet"""
Dim DataToSend
DataToSend= _
"<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:tem=""http://tempuri.org/"">" & _
"<soapenv:Header/>" & _
"<soapenv:Body>" & _
"<tem:Greet>" & _
"<tem:name>John</tem:name>" & _
"</tem:Greet>" & _
"</soapenv:Body>" & _
"</soapenv:Envelope>"
SoapRequest.Send DataToSend
If myXML.load(SoapRequest.responseXML) Then
Dim Node
Set Node = myXML.documentElement.selectSingleNode("//GreetResult")
msgbox Node.Text
Set Node = Nothing
End If
Set SoapRequest = Nothing
Set myXML = Nothing
Might want to double-check the version of the MSXML components. Are you using Windows Authentication? I've noticed some odd XML parsing problems with IIS 7, Classic ASP, and MSXML.
It would also help to get a useful error. Check the ** myXML.parseError.errorCode** and if its not 0 write out the error.
Reference Code:
If (myXML.parseError.errorCode <> 0) then
Response.Write "XML error: " & myXML.parseError.reason
Else
'no error, do whatever here
End If
'You get the idea...