'Image file is not uploaded when send post request with apache http client

I am facing some issues while sending post request with image by using Apache Http client. And getting error sourceFile is not uploaded. But the same post request is working fine in POSTMAN. Please let us know what is the issue in my code ?.

public class ImageUpload {      

      public static void main(String[] args) throws IOException  {

          String path = "G:\\training\\image001.jpg";
            File file = new File(path);
          byte []bytes =
                     Files.readAllBytes(file.toPath());
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);  
            builder.addBinaryBody("sourceFile",bytes);  
            builder.addTextBody("subId", "123457");
            builder.addTextBody("foreignid", "tretrt4ui");
            HttpPost postMethod = new HttpPost("http://localhost:8064/uploaddoc");
            postMethod.setEntity(builder.build());          
            HttpClient client = new DefaultHttpClient();
            postMethod.addHeader("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDIwNDEwODQsInVzZXJfbmFtZSI6ImFkb2xmbyIsImF1dGhvcml0aWVzIjpbIlJPTEVfVVNFUiJdLCJqdGkiOiJkOWVjYTk5YS0xYTNhLTRkYmUtOGQ5Yi05M2E4Y2JkNDQzM2EiLCJjbGllbnRfaWQiOiJjbGllbnRhcHAiLCJzY29wZSI6WyJyZWFkX3Byb2ZpbGUiXX0.UcQVb5lD5A6c3-AqH1JvSKqY8Ibd9tfHnmPhRzvgKb8");
            HttpResponse response = client.execute(postMethod);
            
            HttpEntity respData = response.getEntity();
            try {
            System.out.println(new String(EntityUtils.toByteArray(respData)));
            }
            catch(Exception e) {
                e.printStackTrace();
            }
      }  
  }

enter image description here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source