Alex Chen
Alex Chen

Reputation: 133

read incoming xml in Coldfusion

What I need to write is a script acting like a SOCKET. client post an xml to my endpoint, my script checks if it is a valid xml. I can do this if it is a form upload(knowing input file name). But what if we don't know input name? how to capture the file and check if is it valid xml?

Upvotes: 1

Views: 202

Answers (1)

Alex
Alex

Reputation: 7833

<!--- that's the POST request that was sent to us (supposed to contain XML in body) --->
<cfset httpRequestData = getHttpRequestData()>

<!--- NOTE: you don't need to check the Content-Type, but I consider it to be best practise --->
<cfif (
    structKeyExists(httpRequestData.Headers, "Content-Type") and
    (httpRequestData.Headers["Content-Type"] contains "/xml") <!--- covers "application/xml" and "text/xml" --->
)>

    <!--- in case we receive raw bytes, encode them --->
    <cfif isBinary(httpRequestData.Content)>
        <cfset httpBody = toString(httpRequestData.Content, "UTF-8")>
    <cfelse>
        <cfset httpBody = httpRequestData.Content>
    </cfif>

    <cfif isXml(httpBody)>

        <cfset xmlDoc = xmlParse(httpBody)>

        <cfdump var="#xmlDoc#">

    <cfelse>
        <cfoutput>Error: Body seems to contain malformed XML.</cfoutput>
    </cfif>

<cfelse>
    <cfoutput>Error: No Content-Type provided.</cfoutput>
</cfif>

Upvotes: 1

Related Questions