Read MIME multipart message - java

I hope someone can help me with this. I'm sending a request to server like this:
ClientResponse cr = service.path(url)
.accept(MediaType.MULTIPART_FORM_DATA).get(ClientResponse.class);
As a response I'm receiving a multipart message which looks something like this:
------- =_aaaaaaaaaaA
Content-Type: text/plain; Content-Id: "name"
bkbfdkbfkdbfk3ik3ooijo
------- =_aaaaaaaaaaB
Content-Type: application/octet-stream; Content-Id: "image"
nkniha3q479894ph4934233
My question is how to read those body parts of that message by Id? I need to store every part of that message in a different place.

Related

Receiving both image and JSON in multipart response with Jersey

I try to rebuild the server's response in order to store the received contents (Images and JSON).
The code of the server is like that of here
I changed the server to return TXT files, i get the folowing on the client.
Response response = client.post(body);
logger.info("content :" + response.readEntity(String.class));
--Boundary_9_2112219484_1499871974802
Content-Type: text/plain
Content-Disposition: attachement; filename="file1.txt"
Content of file 1
--Boundary_9_2112219484_1499871974802
Content-Type: text/plain
Content-Disposition: attachement; filename="file2.txt"
Content of file 2
--Boundary_9_2112219484_1499871974802--
Thank you for your help.
I would instead try to base 64 encode the image and then return it as a string in the JSON without any problems.

Uploading JSON string besides File with Ionic native file-transfer plugin to Java JAX-RS Server

I am trying to upload a file to my Java JAX-RS(Jersey) web service.
My method signature on the server side if anyone interested is like this;
upload(#FormDataParam("file") InputStream uploadedStream, #FormDataParam("file") FormDataContentDisposition fileDetail, #FormDataParam("question") String req_question, #Context HttpHeaders headers)
When I try to upload a file with Postman (Client for testing) using multipart/form-data, it is working properly. When I sniff it with Fiddler I see this;
POST http://localhost:8080/application/question/post HTTP/1.1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryT79BovKwL6ObBceu
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
------WebKitFormBoundaryT79BovKwL6ObBceu
Content-Disposition: form-data; name="file"; filename="PARS.png"
Content-Type: image/png
[HERE SOME STRANGE RAW BINARY DATA]
------WebKitFormBoundaryT79BovKwL6ObBceu
Content-Disposition: form-data; name="question"
{"title": "This is title!", "fk_field_id":1}
------WebKitFormBoundaryT79BovKwL6ObBceu--
As you can see it has proper differentation of types of data being sent. But when I try to achieve the same upload with Ionic/Angular my request look like this;
POST http://localhost:8080/application/question/post HTTP/1.1
Content-Type: multipart/form-data
Accept-Language: tr-TR,tr;q=0.8,en-US;q=0.6,en;q=0.4
/Exif II* [SOME STRANGE RAW BINARY DATA]
I only see binary, there is no differentiation nor sign of the params I sent. Here is my Angular code that is responded as failed.
let options: FileUploadOptions =
{
fileKey: 'file',
headers: headers,
params: {"title": "This is title!", "fk_field_id":1} // Actually I am getting this as method parameter yet to shorten code I moved it here
};
path = {MY ENDPOINT IN SERVER}
filePath = file:///storage/emulated/0/Android/data/io.ionic.starter/cache/1497313256081.jpg // Getting as method param
fileTransfer.upload(filePath, path, options).then(things => {
//Some console.log
});

Extract JSON from multi-part HTTP response [duplicate]

I need to receive an HTTP Post Multipart which contains only 2 parameters:
A JSON string
A binary file
Which is the correct way to set the body?
I'm going to test the HTTP call using Chrome REST console, so I'm wondering if the correct solution is to set a "label" key for the JSON parameter and the binary file.
On the server side I'm using Resteasy 2.x, and I'm going to read the Multipart body like this:
#POST
#Consumes("multipart/form-data")
public String postWithPhoto(MultipartFormDataInput multiPart) {
Map <String, List<InputPart>> params = multiPart.getFormDataMap();
String myJson = params.get("myJsonName").get(0).getBodyAsString();
InputPart imagePart = params.get("photo").get(0);
//do whatever I need to do with my json and my photo
}
Is this the way to go?
Is it correct to retrieve my JSON string using the key "myJsonName" that identify that particular content-disposition?
Are there any other way to receive these 2 content in one HTTP multipart request?
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--

MTOM Message parsing

I am getting the below response from a WCF service
--uuid:57cad2b9-196b-4780-9643-cab6131bed98+id=43
Content-ID: <http://tempuri.org/0>
Content-Transfer-Encoding: 8bit
Content-Type: application/xop+xml;charset=utf-8;type="text/xml"
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"><s:Body><DownloadFileResponse xmlns="http://tempuri.org/"><DownloadFileResult xmlns:a="http://schemas.datacontract.org/2004/07/OneC_GenericUploadMessageContract" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><a:EncryptedFileUploadID i:nil="true"/><a:FileContentId i:nil="true"/><a:FileException i:nil="true"/><a:FileExternalURL i:nil="true"/><a:FileLocation i:nil="true"/><a:FileName>176827.jpeg</a:FileName><a:FileURL>C9533C2F-AC59-E411-9405-005056853C65\_00000000-0000-0000-0000-000000000000_56_9_2016_15_11_4_13_636010818640138255.jpeg</a:FileURL><a:FileUploadId>0</a:FileUploadId><a:Filestatus i:nil="true"/><a:OutgoingFile><xop:Include href="cid:http://tempuri.org/1/636029758108722711" xmlns:xop="http://www.w3.org/2004/08/xop/include"/></a:OutgoingFile></DownloadFileResult></DownloadFileResponse></s:Body></s:Envelope>
--uuid:57cad2b9-196b-4780-9643-cab6131bed98+id=43
Content-ID: <http://tempuri.org/1/636029758108722711>
Content-Transfer-Encoding: binary
Content-Type: application/octet-stream
-----binary content here----
i tried parsing this using How to parse XOP/MTOM SOAP response using java?
I am getting boundary missing exception. I am not seeing any boundary specified for this response.
Am i missing something or is this message not properly send?

Cannot consume content type - even with correct #Consumes

I'm working on a REST resource that takes in a key and data (value) . I'd like to be robust so this data can be anything. It could range from a string to a file.
To handle this, I have the PUT REST method which is at the end of the post. Nothing fancy, just trying to PUT basic data. If I send data that is a string it works no problem.
However, if I try to send a file across, I get this error: org.jboss.resteasy.spi.UnsupportedMediaTypeException: Cannot consume content type. Here's why this doesn't make sense to me:
If I change the #Consumes from application/octet-stream to #Consumes("multipart/form-data"), I can send a file across just fine. When examining the file that's stored I see something like this:
------WebKitFormBoundaryfuQalizBHtg1BiLJ
Content-Disposition: form-data; name="fileUpload1"; filename="uploadedFile.extension"
Content-Type: application/octet-stream
/* file information here */
------WebKitFormBoundaryfuQalizBHtg1BiLJ--
Notice that the Content-Type is supposedly application/octet-stream which is what I tried consuming before but got the Cannot consume content type exception. I have no idea what would be causing this. I'm using the Advanced Rest Client extension for Chrome to send my request and it looks something like this: https://i.imgur.com/KvKCIkl.jpg
Any thoughts?
#PUT
#Path("{key}")
#Consumes("application/octet-stream")
public Response addData(
final #PathParam("key") String key,
final InputStream data) {
final Service service = new Service();
try {
service.addData(key, data);
} finally {
IOUtils.closeQuietly(data
}
return Response.status(204).build();
}
A multipart/form-data message contains a series of parts divided by a boundary. Every part has its own Content-Type. So in your example Content-Type: application/octet-stream is the Content-Type of one (and probably the only one) part but the Content-Type of the whole message is multipart/form-data. A full message with multiple parts could look like this:
Content-Type: multipart/form-data; boundary=WebKitFormBoundaryfuQalizBHtg1BiLJ
------WebKitFormBoundaryfuQalizBHtg1BiLJ
Content-Disposition: form-data; name="fileUpload1"; filename="uploadedFile.extension"
Content-Type: application/octet-stream
/* file information here */
------WebKitFormBoundaryfuQalizBHtg1BiLJ--
------WebKitFormBoundaryfuQalizBHtg1BiLJ
Content-Type: text/plain
/* some text here */
------WebKitFormBoundaryfuQalizBHtg1BiLJ--

Categories

Resources