0

I have to make a HTTP POST request with form data to an external API. Currently, I am invoking the API using the below curl command

curl https://books.zoho.com/api/v3/contacts?organization_id=10234695
-X POST
-H "Authorization: Zoho-oauthtoken 216793f385b9dd6e125f"
-H "Content-Type: application/x-www-form-urlencoded;charset=UTF-8"
-F 'JSONString="{
    "contact_name": "Bowman and Co",
    "company_name": "Bowman and Co",
    "website": "www.bowmanfurniture.com",
    "contact_type": "customer"
    }

I have implemented ClientHttpRequestInterceptor interface and registered the interceptor with the RestTemplate. I am not sure, how to post the HTTP request with form data. Kindly let me know, how to submit the form data or point me to any reference.

Inside my Controller class:

@RestController
@RequestMapping("/api/v1/contacts")
public class ContactController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/")

    public Invoice createContact(@RequestBody Contact contact){
        //TODO
        return null;
    }
}
zilcuanu
  • 3,451
  • 8
  • 52
  • 105

1 Answers1

0

You could use a rest template to make a post request with form data.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("data", "data");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

Spring will automatically take care of the message converters used in this case.(The message converter used will be FormHttpMessageConverter). Read Doc

Ananthapadmanabhan
  • 5,706
  • 6
  • 22
  • 39