Home  >  Spring 5

Spring RestTemplate.postForLocation()

By Arvind Rai, April 07, 2020
On this page we will provide Spring postForLocation method example of RestTemplate class. The postForLocation method creates a new resource by posting the given object to given URI template. The postForLocation method returns URI as the value of location header for newly created resource. The postForLocation sends data using HTTP POST method. The postForLocation method is useful when we want the only location header of newly created resource. In postForLocation we can also pass path variables as Map and object variable arguments. Let us discuss the complete example in detail.


1. Technologies Used

Find the technologies being used in our example.
1. Java 11
2. Spring 5.2.5.RELEASE
3. Spring Boot 2.2.6.RELEASE
4. Maven 3.5.2

2. Maven Dependencies

Find the Maven dependencies to run the example.
pom.xml
<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.2.6.RELEASE</version>
	<relativePath />
</parent>
<dependencies>
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-web</artifactId>
	</dependency>
	<dependency>
		<groupId>jakarta.xml.bind</groupId>
		<artifactId>jakarta.xml.bind-api</artifactId>
		<version>2.3.2</version>
	</dependency>
	<dependency>
		<groupId>org.glassfish.jaxb</groupId>
		<artifactId>jaxb-runtime</artifactId>
		<version>2.3.2</version>
	</dependency>
</dependencies> 

3. postForLocation() with URI Variables as Map

Find the postForLocation method declaration with Map as path variable.
URI postForLocation(String url, Object request, Map<String,?> uriVariables) 
url: Template URI to post object.
request: Object to post.
uriVariables: Path variables of request URI.

The postForLocation method returns URI of newly created resource.
Find the example of REST client code.
RestClientUtil.java
package com.concretepage.client;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import com.concretepage.domain.Article;

public class RestClientUtil {
	public void addArticleDemo() {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);

		String url = "http://localhost:8080/user/article/{cat}/{subCat}";

		Map<String, String> map = new HashMap<>();
		map.put("cat", "Spring Security UserDetailsService");
		map.put("subCat", "Mahesh");

		Article objArticle = new Article();
		objArticle.setTitle("Spring Security UserDetailsService");
		objArticle.setWriter("Mahesh");

		HttpEntity<Article> requestEntity = new HttpEntity<>(objArticle, headers);

		RestTemplate restTemplate = new RestTemplate();
		URI uri = restTemplate.postForLocation(url, requestEntity, map);

		System.out.println(uri.getPath());
	}

	public static void main(String args[]) {
		RestClientUtil util = new RestClientUtil();
		util.addArticleDemo();
	}
} 
Find the code for REST web service.
ArticleController.java
package com.concretepage.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriComponentsBuilder;
import com.concretepage.domain.Article;
import com.concretepage.service.ArticleService;

@RestController
@RequestMapping("user")
public class ArticleController {
	@Autowired
	private ArticleService articleService;

	@PostMapping(value = "article/{cat}/{subCat}")
	public ResponseEntity<Void> addArticle(@RequestBody Article article, @PathVariable("cat") String category,
			@PathVariable("subCat") String subCategory, UriComponentsBuilder builder) {

		System.out.println("Category: " + category);
		System.out.println("SubCategory: " + subCategory);

		articleService.addArticle(article);

		HttpHeaders headers = new HttpHeaders();
		headers.setLocation(builder.path("/article/{id}").buildAndExpand(article.getArticleId()).toUri());
		return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
	}
} 
Article.java
package com.concretepage.domain;
public class Article {
	private long articleId;
	private String title;
	private String writer;
        //Setters and Getters
} 
ArticleService.java
package com.concretepage.service;
import org.springframework.stereotype.Service;
import com.concretepage.domain.Article;
@Service
public class ArticleService {
	public void addArticle(Article article) {
		article.setArticleId(101);
		System.out.println("Title: " + article.getTitle());
		System.out.println("Writer: " + article.getWriter());
	}
} 
Output
12:23:25.059 [main] DEBUG org.springframework.web.client.RestTemplate - Response 201 CREATED
/article/101 

In the above example, the content type of request header has been set to JSON. To set content type as XML, find the code.
headers.setContentType(MediaType.APPLICATION_XML) 
To receive the XML data, REST web service Article class will be as following.
@XmlRootElement
public class Article { 
------
} 

4. postForLocation() with URI Variables as Object

Find the postForLocation method declaration with URI variables as objects. We can pass path variables as variable arguments.
URI postForLocation(String url, Object request, Object... uriVariables) 
Find the REST client code.
public void addArticleDemo() {
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON);

	String url = "http://localhost:8080/user/article/{cat}/{subCat}";
	Article objArticle = new Article();
	objArticle.setTitle("Spring Security UserDetailsService");
	objArticle.setWriter("Mahesh");

	HttpEntity<Article> requestEntity = new HttpEntity<>(objArticle, headers);

	String category = "Spring";
	String subCategory = "Spring REST";
	RestTemplate restTemplate = new RestTemplate();
	URI uri = restTemplate.postForLocation(url, requestEntity, category, subCategory);

	System.out.println(uri.getPath());
} 
Web service code will be same as given in the above example.
@PostMapping(value = "article/{cat}/{subCat}")
public ResponseEntity<Void> addArticle(@RequestBody Article article, @PathVariable("cat") String category,
		@PathVariable("subCat") String subCategory, UriComponentsBuilder builder) {
   ------
}
 

5. postForLocation() without URI Variables

Now find the postForLocation method declaration without URI variables.
URI postForLocation(URI url, Object request) 
Find the REST client code.
public void addArticleDemo() throws URISyntaxException {
	HttpHeaders headers = new HttpHeaders();
	headers.setContentType(MediaType.APPLICATION_JSON);

	URI url = new URI("http://localhost:8080/user/article");
	Article objArticle = new Article();
	objArticle.setTitle("Spring Security UserDetailsService");
	objArticle.setWriter("Mahesh");

	HttpEntity<Article> requestEntity = new HttpEntity<>(objArticle, headers);

	RestTemplate restTemplate = new RestTemplate();
	URI uri = restTemplate.postForLocation(url, requestEntity);

	System.out.println(uri.getPath());
} 
Find the web service code snippet.
@PostMapping(value = "article")
public ResponseEntity<Void> addArticle(@RequestBody Article article, UriComponentsBuilder builder) {

	articleService.addArticle(article);

	HttpHeaders headers = new HttpHeaders();
	headers.setLocation(builder.path("/article/{id}").buildAndExpand(article.getArticleId()).toUri());
	return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
} 

6. Run Application

Download the project and run the following command from root folder of the project using command prompt.
mvn spring-boot:run 
Now run RestClientUtil as Java Application.

7. Reference

Spring RestTemplate

8. Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI








©2020 concretepage.com | Privacy Policy | Contact Us