Giriş
Http Post ile belirtilen sınıfı gönderir. Üçüncü parametre sonucun tipini belirtir.
// Without parameters
<T> T postForObject(URI url, @Nullable Object request, Class<T> responseType)
// Parameter object list as var args
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
Object... uriVariables)
// Parameter object list as a map
<T> T postForObject(String url, @Nullable Object request, Class<T> responseType,
Map<String, ?> uriVariables)
postForObject metodu - Parametresiz
ÖrnekŞöyle
yaparız.
String baseUrl = serviceSettings.getUrl();
String result = restTemplate.postForObject(baseUrl, foo, String.class);
Örnek
Todo todoObject = ...;
Todo todoCreated = restTemplate
.postForObject("https://jsonplaceholder.typicode.com/todos", todoObject, Todo.class);
// Or postForEntity
ResponseEntity<Todo> todoResponse = restTemplate
.postForEntity("https://jsonplaceholder.typicode.com/todos", todoObject, Todo.class);
Todo todoInserted = todoResponse.getBody();
System.out.println(todoResponse.getStatusCode().name()); // CREATED
System.out.println(todoResponse.getStatusCodeValue()); // 201
postForObject metodu - Var arg Parametre
Örnek
Order order = ...;
PaymentRequest paymentRequest =...;
// Call payment service
Payment payment = restTemplate
.postForObject("https://payment-service/pay", paymentRequest, Payment.class);
postForObject metodu - Map Parametre
Örnek
Şöyle
yaparız.
public void uploadDocument(byte[] fileContents, final String filename) {
RestTemplate restTemplate = new RestTemplate();
String fooResourceUrl = "http://localhost:8080/spring-rest/foos"; // Dummy URL.
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", filename);
map.add("filename", filename);
// Here we
ByteArrayResource contentsAsResource = new ByteArrayResource(fileContents) {
@Override
public String getFilename() {
return filename; // Filename has to be returned in order to be able to post.
}
};
map.add("file", contentsAsResource);
// Now you can send your file along.
String result = restTemplate.postForObject(fooResourceUrl, String.class, map);
// Proceed as normal with your results.
}