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
352 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

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

AJAX ModalPopupExtender has a required property "TargetControlID" which may seem to be very confusing to new users. It means the server control that will be extended by the ModalPopup, for instance, if when you click a button, a ModalPopup displays,…
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…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

759 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

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now