How to pass binary data in the form fields in Java using HttpClients object

30 Views Asked by At

I have one API which I am trying to automate using HttpClient in Java and I am kind of stuck while forming the request payload. Below is the way payload structure looks. enter image description here Parsed view:

------WebKitFormBoundaryyJ9V86ssAs2cbAe8
Content-Disposition: form-data; name="graph"; filename="blob"
Content-Type: application/json

{"blocks":[{"id":"gjvklw","name":"New Parallel 1","type":"parallel","properties":{"__ACTION_CODE":"fake_action"},"coords":{"x":0,"y":0,"width":255,"height":110,"endY":110}}],"children":{},"connectors":[]}
------WebKitFormBoundaryyJ9V86ssAs2cbAe8
Content-Disposition: form-data; name="smallImage"; filename="blob"
Content-Type: image/png

PNG

IHDRï´½·¤MsRGB®Îé­IDATx^íÝ}|TÕÇñß¹!°ñ'ÕÒªî¨ZêKQ$j­uk
ØV»Ë¶Ûjj·+Ývk}¹­Öº¾jèÖʵU^[´>ôik%   Û®ÚZ«,b27èb$sÏrcÀsBÎÜÏüáKdæw÷ý;øåÜÌÌUÂ@PNuK³ '
------
------
Þ@-@x'{þ= ·C£e@dÞÉ?g à áíàÐh@ Ùw²çÏÙ#8(@x;84ZFH¶áìùsö 
Þ@-ðÿö»<hƨ*IEND®B`

------WebKitFormBoundaryyJ9V86ssAs2cbAe8
Content-Disposition: form-data; name="bigImage"; filename="blob"
Content-Type: image/png

PNG


IHDRà+4.sRGB®Îé IDATx^íÝo]e}ðsö@ D@ TG ³»* u§¶b%eª­3Õuä¾(ÒWâèØÅqú¢øxQ_è¨0Ú«íÐEª¢­3KP³;-L!wO½
M0Ù½ûäløçùì+ÇÜçìïù|Ï9~={÷n]ù"@, PÓ!@,$ ,8? @'  ,8 @tOÒí¬$@E(EÄl @ ]@YH·³! ,³M @te!ÝÎJ P²PDÌ6IÒt;+    @@ÊB1Û$HPÒí¬$@E(EÄl @ ]@YH·
----
----

And this is how I am trying to prepare the payload:

String json = new String(Files.readAllBytes(Paths.get("path_to_json")));
        byte[] jsonSmall = Files.readAllBytes(Paths.get("path_to_png"));
        byte[] jsonBig = Files.readAllBytes(Paths.get("path_to_png"));

        HttpEntity requestEntity = MultipartEntityBuilder.create()
                .addBinaryBody("graph", new ByteArrayInputStream(graph), ContentType.APPLICATION_JSON, "blob")
                .addBinaryBody("smallImage", new ByteArrayInputStream(jsonSmall), ContentType.MULTIPART_FORM_DATA, "blob")
                .addBinaryBody("bigImage", new ByteArrayInputStream(jsonBig), ContentType.MULTIPART_FORM_DATA, "blob")
                .build();

        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(apiUrl);
                httpPost.setEntity(requestEntity);
                // Set Content-Type header
                httpPost.setHeader("Content-Type", "multipart/form-data");
                HttpResponse response = httpClient.execute(httpPost);
                // Handle the response
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("Response Status Code: " + statusCode);
        }

Below is the exception I am getting.

HttpResponseProxy{HTTP/1.1 500 [Date: Mon, 11 Mar 2024 14:00:00 GMT, Content-Type: application/json, Transfer-Encoding: chunked, Connection: keep-alive, Server-Timing: intid;desc=d27644d953d5ed1b, Vary: Origin, Vary: Access-Control-Request-Method, Vary: Access-Control-Request-Headers, X-Content-Type-Options: nosniff, X-XSS-Protection: 0, Cache-Control: no-cache, no-store, max-age=0, must-revalidate, Pragma: no-cache, Expires: 0, Strict-Transport-Security: max-age=31536000 ; includeSubDomains, X-Frame-Options: DENY] ResponseEntityProxy{[Content-Type: application/json,Chunked: true]}}

Any idea please what wrong I am doing here ?

0

There are 0 best solutions below