Solved

vb.net how do I send an xml string to a .aspx page and get the string response?

Posted on 2004-09-10
3
357 Views
Last Modified: 2008-01-09
I am trying to send credit card info to Ipay.  the info is in xml format:

<REQUEST merchantRequestID=''>
  <AUTHENTICATION merchantID="{F44dF8B-D345-48C8}"
password="duck" />
<TRANSACTION action="SALE" fraudScrubLevel="0" effectiveDate="NOW"
transactionDate="NOW" anniversaryDate="NOW" autoCalculateCredit="NO">
  <CARDINFO cardNumber="4111111111111111" expirationMonth="01"
expirationYear="05" cvc2="123" domesticAVS="NONE" internationalAVS="NONE" />
  <CONSUMER firstName="John" lastName="Tester" addr1="123 Main Street"
etc, etc.

I need to send it to https://paysrv.ipay.com/ipay.aspx

that page in turn sends me a response.  the response looks like:

<?xml version="1.0" ?>
- <RESPONSE systemRequestID="82f772d401-ecaf-4b30-88f2" merchantRequestID="" authenticated="True" loaded="1" submitted="1" successful="1" failed="0" processed="1" notes="" status="Created">
- <TRANSACTION action="SALE" amount="15.00"
etc, etc.

basically, how do i go about sending string X and receiving string Y?
0
Comment
Question by:wilbur88
3 Comments
 
LVL 10

Accepted Solution

by:
jnhorst earned 500 total points
ID: 12032525
Here you go:

// this assumes an XmlDocument variable named xmlDoc has been loaded with the XML.
string url = "https://paysrv.ipay.com/ipay.aspx";
WebRequest req = HttpWebRequest.Create(url);
req.Method = "POST";
req.ContentLength = xmlDoc.outerXml.Length;
req.ContentType = "text/xml";

// write xml to the request stream.
StreamWriter sw = new StreamWriter(req.GetRequestStream());
sw.Write(xmlDoc.OuterXml);
sw.Flush;
sw.Close();

// assign credentials if you need to authenticate to the url.
req.Credentials = new NetworkCredentials("username", "password");

// get response.
WebResponse resp = req.GetResponse();

// read response into a stream. this assumes the target will respond with xml.
StreamReader sr = new StreamReader(resp.GetResponseStream());
string xmlRespString = sr.ReadToEnd();
sr.Close();

// load up the response and do whatever with it.
XmlDocument xmlRespDoc = new XmlDocument();
xmlRespDoc.LoadXML(xmlRespString);

// do whatever with the xml document returned.

John



0
 
LVL 17

Expert Comment

by:AerosSaga
ID: 12032678
Heres a "real world" sample:

Public Class USPS

     Private _UserID As String
    Private _Password As String
    Private _ZipOrigin As String
    Private _ZipDestination As String
    Private _DestinationCountry As String

    Public Property ZipOrigin() As String
        Get
            Return _ZipOrigin
        End Get
        Set(ByVal Value As String)
            _ZipOrigin = Value
        End Set
    End Property
    Public Property ZipDestination() As String
        Get
            Return _ZipDestination
        End Get
        Set(ByVal Value As String)
            _ZipDestination = Value
        End Set
    End Property
    Public Property DestinationCountry() As String
        Get
            Return _DestinationCountry
        End Get
        Set(ByVal Value As String)
            _DestinationCountry = Value
        End Set
    End Property

    Public Sub New(ByVal UserID As String, ByVal Password As String)
        _UserID = UserID
        _Password = Password
    End Sub

    Public Function DomesticShippingRate(ByVal ZipOrigin As String, ByVal ZipDestination As String, ByVal Pounds As Single, ByVal Ounces As Single) As Single
        Dim xmlRequest As New Text.StringBuilder(75)
        Dim xmlResponse As New Xml.XmlDocument
        Dim xmlHTTPRequest As System.Net.HttpWebRequest
        Dim xmlHTTPResponse As System.Net.HttpWebResponse

        xmlRequest.Append("API=Rate&XML=<RateRequest USERID=""" & _UserID & """ PASSWORD=""" & _Password & """>")
        xmlRequest.Append("<Package ID=""0""><Service>Priority</Service>")
        xmlRequest.Append("<ZipOrigination>" & ZipOrigin & "</ZipOrigination>")
        xmlRequest.Append("<ZipDestination>" & ZipDestination & "</ZipDestination>")
        xmlRequest.Append("<Pounds>" & Pounds & "</Pounds>")
        xmlRequest.Append("<Ounces>" & Ounces & "</Ounces>")
        xmlRequest.Append("<Container>None</Container><Size>Regular</Size><Machinable>False</Machinable>")
        xmlRequest.Append("</Package></RateRequest>")

        xmlHTTPRequest = xmlHTTPRequest.Create("http://Production.ShippingAPIs.com/ShippingAPI.dll?" & xmlRequest.ToString())
        xmlHTTPRequest.Timeout = 5000

        Try
            xmlHTTPResponse = xmlHTTPRequest.GetResponse()
            xmlResponse.Load(xmlHTTPResponse.GetResponseStream())
            If xmlResponse.DocumentElement.FirstChild.FirstChild.Name = "Error" Then
                Throw New USPSException("The USPS server returned the following error: " & _
                  xmlResponse.SelectSingleNode("/RateResponse/Package/Error/Description").InnerText)
            Else
                Return xmlResponse.SelectSingleNode("/RateResponse/Package/Postage").InnerText
            End If
        Catch ex As USPSException
            Throw ex
        Catch ex As Net.ProtocolViolationException
            Throw New USPSException("A timeout occurred while contacting the USPS server.")
        Catch ex As Net.WebException
            Throw New USPSException("The USPS server did not return any data. Please try again later.")
        End Try
    End Function
    Public Function DomesticShippingRate(ByVal ZipOrigin As String, ByVal ZipDestination As String, ByVal WeightInPounds As Single) As Single
        Dim Pounds, Ounces As Single

        Pounds = Math.Floor(WeightInPounds)
        Ounces = Math.Round((WeightInPounds - Math.Floor(WeightInPounds)) * 16)

        Return DomesticShippingRate(ZipOrigin, ZipDestination, Pounds, Ounces)
    End Function

    Public Function InternationalShippingRate(ByVal strDestination As String, ByVal Pounds As Single, ByVal Ounces As Single) As Single
        Dim xmlRequest As New Text.StringBuilder(75)
        Dim xmlResponse As New Xml.XmlDocument
        Dim xmlHTTPRequest As System.Net.HttpWebRequest
        Dim xmlHTTPResponse As System.Net.HttpWebResponse
        Dim Service As Xml.XmlElement

        xmlRequest.Append("API=IntlRate&XML=<IntlRateRequest USERID=""" & _UserID & """ PASSWORD=""" & _Password & """>")
        xmlRequest.Append("<Package ID=""0"">")
        xmlRequest.Append("<Pounds>" & Pounds & "</Pounds>")
        xmlRequest.Append("<Ounces>" & Ounces & "</Ounces>")
        xmlRequest.Append("<MailType>Package</MailType>")
        xmlRequest.Append("<Country>" & DestinationCountry & "</Country>")
        xmlRequest.Append("</Package></IntlRateRequest>")

        xmlHTTPRequest = xmlHTTPRequest.Create("http://Production.ShippingAPIs.com/ShippingAPI.dll?" & xmlRequest.ToString())
        xmlHTTPRequest.Timeout = 5000

        Try
            xmlHTTPResponse = xmlHTTPRequest.GetResponse()
            xmlResponse.Load(xmlHTTPResponse.GetResponseStream())

            If xmlResponse.DocumentElement.FirstChild.FirstChild.Name = "Error" Then
                Throw New USPSException("The USPS server returned the following error: " & _
                  xmlResponse.SelectSingleNode("/IntlRateResponse/Package/Error/Description").InnerText)
            Else
                Try
                    Return xmlResponse.SelectSingleNode("/IntlRateResponse/Package/Service/Postage[" & _
                      "following-sibling::SvcDescription[contains(text(),'(EMS)')]]").InnerText
                Catch ex As NullReferenceException
                    Return xmlResponse.SelectSingleNode("/IntlRateResponse/Package/Service/Postage[" & _
                      "following-sibling::SvcDescription[contains(text(),'Airmail Parcel Post')]]").InnerText
                End Try
            End If

        Catch ex As Net.ProtocolViolationException
            Throw New USPSException("A timeout occurred while contacting the USPS server.")
        Catch ex As Net.WebException
            Throw New USPSException("The USPS server did not return any data. Please try again later.")
        End Try
    End Function
    Public Function InternationalShippingRate(ByVal strDestination As String, ByVal WeightInPounds As Single) As Single
        Dim Pounds, Ounces As Single

        Pounds = Math.Floor(WeightInPounds)
        Ounces = Math.Round((WeightInPounds - Math.Floor(WeightInPounds)) * 16)

        Return InternationalShippingRate(_DestinationCountry, Pounds, Ounces)
    End Function

End Class

I hope this helps I have written many modular classes for just such operations.  A lot of business communications occour this way.

Regards,

Aeros
0
 

Author Comment

by:wilbur88
ID: 12032734
Thanks for the quality quick response John!

And thanks Aeros-  unfortunately I was accepting John's answer when I see yours.
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In an ASP.NET application, I faced some technical problems. In this article, I list them out and show the solutions that I found.  I hope it will be useful. Problem: After closing a pop-up window, the parent page should be refreshed automaticall…
IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
In a recent question (https://www.experts-exchange.com/questions/28997919/Pagination-in-Adobe-Acrobat.html) here at Experts Exchange, a member asked how to add page numbers to a PDF file using Adobe Acrobat XI Pro. This short video Micro Tutorial sh…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

825 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