How can I pass JSON as well as File to REST API in JAVA?
Asked Answered
G

3

7

My main question is how can I pass JSON as well as File to post request to REST API? What needs in Spring framework to work as client and wait for response by passing post with JSON and File?

Options:

  1. Do I need to use FileRepresentation with ClientResource? But how can I pass file as well as JSON?
  2. By using RestTemplate for passing both JSON as well as File? How it can be used for posting JSON as well as File?

Any other option is available?

Goyette answered 19/12, 2012 at 13:20 Comment(0)
M
1

Sounds like an awful resource you're trying to expose. My suggestion is to separate them into 2 different requests. Maybe the JSON has the URI for the file to then be requested…

Milore answered 19/12, 2012 at 13:25 Comment(3)
Well the problem is to pass JSON and File in one REST API request only. This is required and necessary for working properly. How can I pass file in URI?Goyette
That sounds like an interesting requirement. Can you brief on why that's necessary?Perfectionist
Well the request for REST API is such that it requires JSON as well as file to be passed in request. How that could be possible in single request?Goyette
P
1

From a REST(ish) perspective, it sounds like the resource you are passing is a multipart/mixed content-type. One subtype will be application/json, and one will be whatever type the file is. Either or both could be base64 encoded.

You may need to write specific providers to serialize/deserialize this data. Depending on the particular REST framework, this article may help.

An alternative is to create a single class that encapsulates both the json and the file data. Then, write a provider specific to that class. You could optionally create a new content-type for it, such as "application/x-combo-file-json".

Parolee answered 19/12, 2012 at 17:2 Comment(0)
R
1

You basically have three choices:

  1. Base64 encode the file, at the expense of increasing the data size by around 33%.
  2. Send the file first in a multipart/form-data POST, and return an ID to the client. The client then sends the metadata with the ID, and the server re-associates the file and the metadata.
  3. Send the metadata first, and return an ID to the client. The client then sends the file with the ID, and the server re-associates the file and the metadata.
Racoon answered 20/2, 2018 at 7:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.