How to post an image in Java

There are many API endpoints which expect images or files to be submitted as part of the body. In Java we can do that easily using HTTP client library. Here is the sample code :

try { CloseableHttpClient httpclient = HttpClients.createDefault(); HttpPost httppost = new HttpPost( “https://node-01.faceapp.io/api/v2.6/photos”); httppost.setHeader(“User-Agent”, “FaceApp/2.0.561 (Linux; Android 6.0)”); httppost.setHeader(“X-FaceApp-DeviceID”, “abc4fghr”);   File file = new File(“C:\\Downloads\\pics\\Social\\f025cd8b-576e-4941-a4e1-911139754c41.jpg”);   MultipartEntity mpEntity = new MultipartEntity(); ContentBody cbFile = new FileBody(file, “image/jpeg”); mpEntity.addPart(“Image”, cbFile);   httppost.setEntity(mpEntity);   CloseableHttpResponse response = httpclient.execute(httppost); System.out.println(response.getStatusLine());   HttpEntity entity = response.getEntity(); EntityUtils.consume(entity); response.close(); } catch (IOException ex) { // Logger.getLogger(VentanaPrincipal.class.getName()).log(Level.SEVERE, // null, ex); }

Leave a Reply

Your email address will not be published. Required fields are marked *