ColdFusion, CFHTTP, and java.io.ByteArrayOutputStream

I believe I may have blogged this before, but a reader ran into this yesterday so I thought it might be worth sharing. If you are using CFHTTP to hit a remote and seeing java.io.ByteArrayOutputStream in the result, there is a simple solution around that.

Here is a sample cfdump of just such a response. You are expecting a string of some sort in fileContent, but instead end up with a Java object:

unnamed

To work with this result as a string, you simply need to run toString() on the value. So for example, if you know the response is JSON:

deserializeJSON(result.filecontent.toString())

I'll be honest and say I don't know why some servers return that, or why cfhttp can't simply toString it itself. I'm assuming there is a good reason that probably involves all kind of crap I really don't care about. ;)

p.s. It looks like this might be just ColdFusion 9 and earlier - see this bug report. I can say it has been a while since I've seen it. I've run ColdFusion 10 since it came out pretty much.

Archived Comments

Comment 1 by Doug Sims posted on 12/13/2014 at 4:59 AM

I see this a lot working with REST APIs. This is due to the server sending g-ziped data in the post data.

Comment 2 (In reply to #1) by Adam Tuttle posted on 12/13/2014 at 5:29 AM

It's not just for gzip. I've seen it depend specifically on the Content-Type of the response in APIs I've created. Using "application/json" would make CF expose it as binary, whereas if I changed that to "text/json" CF would expose it as text.

Comment 3 by Raffael Meier posted on 7/19/2018 at 6:45 PM

"....probably involves all kind of crap I really don’t care about. ;)" -> very nicely said! directly out of my heart.

Comment 4 (In reply to #3) by Raymond Camden posted on 7/19/2018 at 6:56 PM

I'm honest. ;)

Comment 5 (In reply to #2) by Raymond Camden posted on 7/19/2018 at 6:56 PM

I wonder if CF ever fixed that.