FileBody java code example

Example 1: Filebody in java

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);

MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("bin", bin);
reqEntity.addPart("comment", comment);
httppost.setEntity(reqEntity);

HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();

Example 2: Filebody in java

public static void postFile(String fileName) throws Exception {//fileName is path+filename of picture
   String url_upload_image = "http://url-to-api/upload_photo.php";
   HttpClient client = new DefaultHttpClient();
   HttpPost post = new HttpPost(url_upload_image);
   MultipartEntityBuilder multipartEntity = MultipartEntityBuilder
       .create();
   multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
   multipartEntity.addPart("file", new FileBody(new File(fileName)));
   post.addHeader("id", id);//id is anything as you may need
   post.setEntity(multipartEntity.build());
   HttpResponse response = client.execute(post);
   HttpEntity entity = response.getEntity();
   entity.consumeContent();
   client.getConnectionManager().shutdown();
 }

Tags:

Java Example