How to POST form data with Spring RestTemplate?

To POST form data with the RestTemplate class in Spring, you can use the postForObject method and pass it a URL, an object containing the form data, and the response type.

Here's an example of how you can POST form data with RestTemplate:

import org.springframework.web.client.RestTemplate;

public class Main {
  public static void main(String[] args) {
    RestTemplate restTemplate = new RestTemplate();

    // create a map to store the form data
    Map<String, String> formData = new HashMap<>();
    formData.put("username", "john");
    formData.put("password", "secret");

    // POST the form data to the server
    String result = restTemplate.postForObject("http://example.com/login", formData, String.class);

    // print the result
    System.out.println(result);
  }
}

This code creates a RestTemplate object and a map to store the form data. It then uses the postForObject method to POST the form data to the server, and specifies the response type as String. The postForObject method returns the server's response as a String, which is printed to the console.

Note that the postForObject method is just one of the several methods provided by RestTemplate for making HTTP requests. You can also use the postForEntity, postForLocation, or postForLocation methods, depending on your needs.