Extract multiple JSON strings from multipart HTTP response

605 views Asked by At

I'm using Apache HttpClient to work with a web service that returns a multipart/form-data response which contains json.

I'm having a very hard time extracting each JSON string separately so I can read the json string.

I did read similar posts on Stackoverflow, and some suggested using Apache commons fileupload, but I am not sure how that can separate the JSON strings from the whole response that has a bunch of other text such as the boundary string, content type, etc

The response looks something like below.

--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetMailboxes
Status-Code: 200
X-Server-Response-Time: 4ms
X-Server-Chain: domain.com
Content-RequestDuration: 5

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetFolders
Status-Code: 200
X-Server-Response-Time: 8ms
X-Server-Chain: domain.com
Content-RequestDuration: 10

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetAlerts
Status-Code: 200
X-Server-Response-Time: 10ms
X-Server-Chain: domain.com
Content-RequestDuration: 12

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetAccounts
Status-Code: 200
X-Server-Response-Time: 11ms
X-Server-Chain: domain.com
Content-RequestDuration: 12

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetAllSavedSearches
Status-Code: 200
X-Server-Response-Time: 10ms
X-Server-Chain: domain.com
Content-RequestDuration: 12

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetAthenaSegment
Status-Code: 200
X-Server-Response-Time: 14ms
Content-RequestDuration: 21

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: ListFolderThreads
Status-Code: 200
X-Server-Response-Time: 110ms
Content-RequestDuration: 116

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-Type: application/json
Content-RequestId: GetUserInfo
Status-Code: 200
X-Server-Response-Time: 197ms
Content-RequestDuration: 204

{JSON}
--Boundary_16003419_2104021487_1483424496169
Content-RequestId: Status
Content-Type: application/json

{JSON}
--Boundary_16003419_2104021487_1483424496169--

Any way to do this reliably?

1

There are 1 answers

0
ok2c On

One option would be Apache Mime4j. You would likely want to use MimeTokenStream or MimeStreamParser as described here if you want your application to handle response content without building a complete DOM tree in memory.