4

I am able to post this request using a REST client (Insomnia). However, when I unable to write a proper code to do the same in Java. Below is how my insomnia request looks like.

enter image description here

Below is how the code generated by the Client looks like.

HttpResponse<String> response = Unirest.post("http://172.16.6.15:5053/image-service/services/image-panel-service/panel/images?=")
  .header("com.yatra.tenant.header.tenantid", "1051")
  .header("content-type", "multipart/form-data; boundary=---011000010111000001101001")
  .body("-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"imageFile\"\r\n\r\n")
  .asString();

Below is the code I have written in Java which doesn't work.

try {
            HttpResponse<String> response = Unirest.post("http://172.16.6.15:5053/image-service/services/image-panel-service/panel/images")
            .header("com.yatra.tenant.header.tenantid", "1051")
            .header("content-type", "multipart/form-data")
            .field("imageFile", new File("Desert.jpg"))
            .field("imageData", new File("ImageUploadRequest.json")).asString();

            System.out.println(response.getBody());

        } catch (UnirestException e) {
            e.printStackTrace();
        }
Bharat Nanwani
  • 653
  • 4
  • 11
  • 27

2 Answers2

6

Snippet from their documentation http://kong.github.io/unirest-java/#file-uploads

 Unirest.post("http://httpbin.org")
   .field("imageFile", new File("JellyFirst.jpg"))
   .asEmpty();
4
try {
    MultipartBody body = Unirest.post("http://localhost:4849/upload/images")
        .field("name", "bingoo.txt")
        .field("files", temp1)
        .field("files", temp2)
        .field("files", temp3);
    HttpResponse<String> file = body.asString();
    System.out.println(file.getStatus());

} catch (Exception e) {
    e.printStackTrace();
}

snippet from https://www.programcreek.com/java-api-examples/?api=com.mashape.unirest.request.body.MultipartBody

Anshul Kataria
  • 956
  • 8
  • 8