Solved

XML over HTTP in VB.NET / ASP.NET

Posted on 2008-10-29
7
4,573 Views
Last Modified: 2013-11-18
I have two separate applications that talk to each other using basic XML over HTTP (currently written in vbscript/ASP and COM+)  I need to be able to add a middle process between the two apps written in ASP.NET/VB.NET that consumes the XML over HTTP from the first process, does some database interactivity and then sends the XML over HTTP on to the second process.  I'm pretty educated on how to use the standard ASP.NET Web Services and I have code to "send" XML over HTTP in .NET but not to "consume" it.

My Questions are:
1.  How can I consume XML over HTTP with .NET (I have code below that sends it successfully)
2.  Can I just use standard ASP.NET Web Services (ASMX files) to do all this somehow?
Public Function PostXml(ByVal url As String, ByVal xml As String) As String

        Dim returnValue As String = ""

        Try

            Dim bytes As Byte() = Encoding.UTF8.GetBytes(xml)

            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)

            request.Method = "POST"

            request.ContentLength = bytes.Length

            request.ContentType = "text/xml"

            Using requestStream As Stream = request.GetRequestStream()

                requestStream.Write(bytes, 0, bytes.Length)

            End Using
 

            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

            If response.StatusCode <> HttpStatusCode.OK Then

                Dim message As String = [String].Format("POST failed. Received HTTP {0}", response.StatusCode)

                Throw New ApplicationException(message)

            End If

            Dim rs As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

            Dim receiveStream As Stream = rs.GetResponseStream()

            Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")

            Dim readStream As New StreamReader(receiveStream, encode)

            Dim read(256) As [Char]

            Dim count As Integer = readStream.Read(read, 0, 256)

            While count > 0

                Dim str As New [String](read, 0, count)

                returnValue += str

                count = readStream.Read(read, 0, 256)

            End While

            readStream.Close()

            rs.Close()

        Catch ex As Exception

            Return ex.Message

        End Try

        Return returnValue

    End Function

Open in new window

0
Comment
Question by:edenmachine
  • 4
  • 3
7 Comments
 
LVL 19

Accepted Solution

by:
drichards earned 500 total points
ID: 22837682
You could use a generic handler (ashx).  On the middle machine, create an empty web project and add a generic handler.  This will create an ashx file.  You can post the XML to this file and do whatever you need.  You just read the request input in the same way as you are reading the response stream in the code you posted.  Depending on what you're doing with the XML, you can use an XmlReader or an XmlDocument to process the XML.  Use thel latter if you need to do XSLT or other whole-document processing and the former if you are just parsing through the XML looking for certain data.

The web service (asmx) file is not what you want because you do not have a full web service with SOAP and all.  You are just posting your XML document directly.
0
 
LVL 1

Author Comment

by:edenmachine
ID: 22841084
I get this error everytime I try to post to the asmx page:

The remote server returned an error: (401) Unauthorized.
 
I've posted my code below but I've tried all kinds of things to get any kind of a response and I only get the above error.

ASPX PAGE:
 

<%@ Page Language="VB" %>

<%@ Import Namespace="System.Net" %>

<%@ Import Namespace="System.IO" %>
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 

<script runat="server">
 

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)

        Response.Write(PostXml("http://vm01/sign/testxmloverhttp/listener.ashx", My.Computer.FileSystem.ReadAllText(Server.MapPath("XMLFile.xml"), Encoding.UTF8)))

    End Sub

    

    Public Function PostXml(ByVal url As String, ByVal xml As String) As String

        Dim returnValue As String = ""

        Try

            Dim bytes As Byte() = Encoding.UTF8.GetBytes(xml)

            Dim request As HttpWebRequest = DirectCast(WebRequest.Create(url), HttpWebRequest)

            request.Method = "POST"

            request.ContentLength = bytes.Length

            request.ContentType = "text/xml"

            Using requestStream As Stream = request.GetRequestStream()

                requestStream.Write(bytes, 0, bytes.Length)

            End Using
 

            Dim response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

            If response.StatusCode <> HttpStatusCode.OK Then

                Dim message As String = [String].Format("POST failed. Received HTTP {0}", response.StatusCode)

                Throw New ApplicationException(message)

            End If

            Dim rs As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)

            Dim receiveStream As Stream = rs.GetResponseStream()

            Dim encode As Encoding = System.Text.Encoding.GetEncoding("utf-8")

            Dim readStream As New StreamReader(receiveStream, encode)

            Dim read(256) As [Char]

            Dim count As Integer = readStream.Read(read, 0, 256)

            While count > 0

                Dim str As New [String](read, 0, count)

                returnValue += str

                count = readStream.Read(read, 0, 256)

            End While

            readStream.Close()

            rs.Close()

        Catch ex As Exception

            Return ex.Message

        End Try

        Return returnValue

    End Function

</script>
 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    

    </div>

    </form>

</body>

</html>
 

ASHX PAGE:
 

<%@ WebHandler Language="VB" Class="Listener" %>
 

Imports System

Imports System.Web
 

Public Class Listener : Implements IHttpHandler

    

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        context.Response.ContentType = "text/xml"

        context.Response.Write(context.Request.Form)

    End Sub

 

    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable

        Get

            Return False

        End Get

    End Property
 

End Class

Open in new window

0
 
LVL 19

Expert Comment

by:drichards
ID: 22841532
What exactly are you doing here?  Why use the aspx page at all?  The ashx will handle the request directly and not have the overhead of all the Page junk that you don't need here.  Or is that page something else?  As for the 401 error, you evidently have not granted appropriate access to the virtual directory in IIS so you can browse call the app.  I'd have to know more about how you configured things to say how to fix it.
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 1

Author Comment

by:edenmachine
ID: 22841612
I don't have any problem accessing the ASHX when I type in http://vm01/sign/testxmloverhttp/listener.ashx directly into the browser so I'm not sure why there would be a permissions problem.  The ASPX page is just to mock the posting of the XML that would be posted XML over HTTP from the First Process that the ASHX needs to "intercept" before continuing on to the Second Process.
0
 
LVL 1

Author Comment

by:edenmachine
ID: 22841636
I can definitely agree with you that the ASHX was the solution to my original problem so I'm giving you the full points.  I guess maybe I need to ask a separate question about my permissions issue.  thanks!
0
 
LVL 19

Expert Comment

by:drichards
ID: 22844573
You can continue here with the permissions if you want.  How do you have IIS configured for that folder and where are you sending the tests requests from (both browser and program)?
0
 
LVL 1

Author Comment

by:edenmachine
ID: 22844606
I figured it out - I had to grant "Users" perms to that file/directory and then it worked fine - thanks for your help!
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
Introduction Since I wrote the original article about Handling Date and Time in PHP and MySQL (http://www.experts-exchange.com/articles/201/Handling-Date-and-Time-in-PHP-and-MySQL.html) several years ago, it seemed like now was a good time to updat…
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

861 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

22 Experts available now in Live!

Get 1:1 Help Now