Monday, 26 August 2019

How to send file with secure web service

We might have called many secure/plain web services with tokens/without tokens. But sending a file to secure web service with token is little tricky,  follow the below simple steps to invoke a secure web service with token and send file .




//Create an object for OkHttpClient , this is available from java1.8
OkHttpClient client = new OkHttpClient();

// Create a file object for the file which you would like to send along with the web service call
File file= new File("D:\\test\\ExampleContacts_Hanuman.csv");

//Create the request body using MultipartBody and provide the files details to request body .
RequestBody formBody = new MultipartBody.Builder()
        .setType(MultipartBody.FORM)
        .addFormDataPart("file", file.getName(),
            RequestBody.create(MediaType.parse("text/plain"), file))
        .addFormDataPart("other_field", "other_field_value")
        .build();

// Bild the compelte request with URL , token and request body
Request request = new Request.Builder()
  .url("https://securewebservicewithFile********.com")
  .post(formBody)
  .addHeader("Content-Type", "multipart-formdata")
  .addHeader("x-api-token", "apitoekn*******")
  .addHeader("cache-control", "no-cache")
  .build();

// Invoke the request
Response response = client.newCall(request).execute();
//Verify the reponse ..
System.out.println(" response"+ response);



Its so simple to send file with OkHttpClient for secure web service.
Hope this will helpful.