Friday, March 9, 2012

Another way to consume a webservice

We have discussed earlier the standard and suggested way of how to consume the webservice. The URL for the same is below:

To consume the webservice this way, needs us to have the wsdl link defined. Consider the case in which the service provider is not providing the webservice through wsdl. You will not be able to create the reference to the webservice in that case from visual studio and cannot move further to consume the webservice.

We will take an example of the Webservice for Exchange Rate by Yahoo which we can call directly without the creation of reference to it and get the exchange rate of USD to INR as shown below:

static void ExchRateTest(Args _args)
    Currency                    currency;
    str                         url;
    str                         exchRate = "";
    str                         fromCurrency, toCurrency;

    System.Net.HttpWebRequest   httpRequest  = null;
    System.Net.HttpWebResponse  httpResponse = null;
    CLRObject                   clro         = null;
    System.IO.Stream            stream       = null;
    System.IO.StreamReader      streamReader = null;

    fromCurrency    = 'USD';
    toCurrency      = 'INR';

    url = "" + fromCurrency + toCurrency + "=X";

        new InteropPermission(InteropKind::ClrInterop).assert();
        clro         = System.Net.WebRequest::Create(url);
        httpRequest  = clro;
        httpResponse = httpRequest.GetResponse();
        stream = httpResponse.GetResponseStream();
        streamReader = new System.IO.StreamReader(stream);
        exchRate = streamReader.ReadToEnd();

        info(strFmt("%1 to %2 - %3",fromCurrency,toCurrency,exchRate));
        throw error(AifUtil::getClrErrorMessage());

Below is the output of the code:
USD to INR - 49.755

No comments:

Post a Comment