Hi everyone, I will share about how to post a file as a multipart request along with other multipart parameters.
So, I was working on a project and previously I was using like RestTemplate library by spring, but the call was failing and I was not able to post data to rest API. I tried like changing header, changing the format of request body and looked over different blogs, but no use.
So what I did like, I tried to make the call from the postman and it worked. From there I used the code option to get the related code to mimic the call in java. From there I got to know about a library, OkHttp which is a rest library for java and android. I got the sample code from Postman.
Note: Generating code is a feature provided by postman. It helps by generating a code for a relevant language and give us idea on like on how it should be done in the respective language. For example i generated OkHttp code.
The sample code from the postman can be seen in the below image. (Code generator from postman)
So this code above you see, gave me the idea of using OkHttp in place of RestTemplate.
So let see how to use the OkHttpCode.
- First Initialize the OkHttp Client.
- Then Create Request Body by adding required multipart parameters.
- Creating the request by passing the API URL and request body we just created.
- Create a response and execute API.
- Handle the response and the data from Response.
Or you can see the code snippet below for the same.
So this is all for now, hope this helps you and solve your problem. Stay connected for more posts.
Also, check my blog for more posts and our publication Tekraze.