Tuesday, August 9, 2016

Java client to send a file or inputstream to Jersey Restful API

5:39 PM

We  often run in the need of Java client where we can send a file to Restful web services. To do so we will need a multi part request and send it to api. Below code demonstrate how to do it using java.



package com.test;

import java.io.File;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.HttpClientBuilder;

public class JavaClient {

 public int callAPI() throws Exception {
  String url = "http://localhost:8080/testAPI/rest/fileupload";
  HttpClient httpclient = HttpClientBuilder.create()
    .disableContentCompression().build();
  HttpPost httppost = new HttpPost(url);
  MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
  reqEntity.addBinaryBody("file", new File(""));
  httppost.setEntity(reqEntity.build());
  HttpResponse response = httpclient.execute(httppost);
  int statuscode = response.getStatusLine().getStatusCode();
  return statuscode;
 }

}


You can also use InputStream instead of File if you don't want to send File.

To send the inputstream instead of file please replace the statement  reqEntity.addBinaryBody("file", new File(filePath));

with reqEntity.addBinaryBody("file", fileIPStream); in above code snippet. 


0 comments :

Post a Comment

 

© 2014 DieHardTechy . All rights resevered. Designed by Diehardtechy