RestTemplate হলো স্প্রিং ফ্রেমওয়ার্কের একটি সিঙ্ক্রোনাস ক্লায়েন্ট, যা HTTP প্রোটোকল ব্যবহার করে RESTful ওয়েব সার্ভিসের সাথে যোগাযোগের জন্য ব্যবহৃত হয়। এটি স্প্রিং 3.0 এ পরিচিত হয় এবং Spring Boot-এ খুব জনপ্রিয়ভাবে ব্যবহৃত হয় REST API কল করার জন্য।
RestTemplate স্প্রিং ফ্রেমওয়ার্কের অংশ, তাই আলাদা ডিপেনডেন্সি যোগ করার প্রয়োজন নেই। শুধুমাত্র Spring Web
ডিপেনডেন্সি থাকলেই যথেষ্ট।
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
RestTemplate ব্যবহারের আগে এটিকে বীন হিসেবে সংজ্ঞায়িত করতে পারেন। সাধারণত @Configuration
ক্লাসে এটি করা হয়।
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
REST API থেকে ডেটা আনার জন্য getForObject()
বা getForEntity()
ব্যবহার করা হয়।
@RestController
@RequestMapping("/api/client")
public class ApiController {
private final RestTemplate restTemplate;
public ApiController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@GetMapping("/get-data")
public String getData() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
return restTemplate.getForObject(url, String.class);
}
}
নতুন ডেটা সার্ভারে পাঠানোর জন্য postForObject()
বা postForEntity()
ব্যবহার করা হয়।
@PostMapping("/send-data")
public String sendData() {
String url = "https://jsonplaceholder.typicode.com/posts";
Map<String, String> requestBody = new HashMap<>();
requestBody.put("title", "foo");
requestBody.put("body", "bar");
requestBody.put("userId", "1");
return restTemplate.postForObject(url, requestBody, String.class);
}
বিদ্যমান ডেটা আপডেট করতে put()
ব্যবহার করা হয়।
@PutMapping("/update-data")
public void updateData() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
Map<String, String> requestBody = new HashMap<>();
requestBody.put("id", "1");
requestBody.put("title", "updated title");
requestBody.put("body", "updated body");
requestBody.put("userId", "1");
restTemplate.put(url, requestBody);
}
ডেটা মুছে ফেলতে delete()
ব্যবহার করা হয়।
@DeleteMapping("/delete-data")
public void deleteData() {
String url = "https://jsonplaceholder.typicode.com/posts/1";
restTemplate.delete(url);
}
Method | ব্যবহার |
---|---|
getForObject() | URL থেকে ডেটা ফেচ করে এবং একটি অবজেক্টে রিটার্ন করে। |
getForEntity() | URL থেকে ডেটা ফেচ করে এবং ResponseEntity রিটার্ন করে। |
postForObject() | POST অনুরোধ পাঠিয়ে এবং অবজেক্ট রিটার্ন করে। |
postForEntity() | POST অনুরোধ পাঠিয়ে এবং ResponseEntity রিটার্ন করে। |
put() | PUT অনুরোধ পাঠিয়ে ডেটা আপডেট করে। |
delete() | DELETE অনুরোধ পাঠিয়ে ডেটা ডিলিট করে। |
exchange() | কাস্টম HTTP মেথড কলের জন্য ব্যবহৃত হয়। |
execute() | নিম্নস্তরের HTTP কল পরিচালনা করতে ব্যবহৃত হয়। |
স্প্রিং ৫.০ থেকে WebClient ব্যবহার করার পরামর্শ দেওয়া হয় কারণ এটি Reactive Programming সমর্থন করে এবং নন-ব্লকিং I/O এর মাধ্যমে আরও ভালো পারফরম্যান্স প্রদান করে।
যদি RestTemplate এর পরিবর্তে WebClient সম্পর্কে বিস্তারিত জানতে চান, জানাতে পারেন! 😊
RestTemplate
হলো Spring Framework-এ সরবরাহকৃত একটি ক্লাস যা HTTP-ভিত্তিক RESTful API-র সাথে যোগাযোগের জন্য ব্যবহার করা হয়। এটি Spring 3.0 তে চালু করা হয়েছিল এবং Spring Boot সহ Spring এর যেকোনো অ্যাপ্লিকেশনে সহজে RESTful কমিউনিকেশন করতে দেয়।
GET
, POST
, PUT
, DELETE
, PATCH
ইত্যাদি HTTP মেথড সমর্থন করে।GET
অনুরোধ:import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateExample {
private final RestTemplate restTemplate;
public RestTemplateExample(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getExampleData(String url) {
return restTemplate.getForObject(url, String.class); // JSON রেসপন্স String হিসাবে ফেরত দিবে
}
}
POST
অনুরোধ:import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateExample {
private final RestTemplate restTemplate;
public RestTemplateExample(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String postExampleData(String url, Object requestPayload) {
ResponseEntity<String> response = restTemplate.postForEntity(url, requestPayload, String.class);
return response.getBody();
}
}
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class RestTemplateExample {
private final RestTemplate restTemplate;
public RestTemplateExample(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getDataWithParams(String url, Map<String, String> params) {
return restTemplate.getForObject(url, String.class, params);
}
}
Spring Boot-এ RestTemplate
-এর জন্য একটি @Bean
তৈরি করা হয়:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
RestTemplate
-কে deprecated করা হতে পারে এবং এর পরিবর্তে WebClient
ব্যবহারের পরামর্শ দেওয়া হচ্ছে।Spring WebFlux-এ WebClient
হলো RestTemplate-এর আধুনিক এবং নন-ব্লকিং বিকল্প। যদি আপনার অ্যাপ্লিকেশন রিয়্যাকটিভ বা অ-সিঙ্ক্রোনাস আচরণ প্রয়োজন করে, তাহলে WebClient
ব্যবহার করা ভালো।
RestTemplate
একটি শক্তিশালী এবং সহজ টুল HTTP API কল করার জন্য। যদিও এটি ক্লাসিকাল অ্যাপ্লিকেশন ডিজাইনের জন্য কার্যকর, ভবিষ্যতের প্রজেক্টে WebClient
ব্যবহারের দিকে নজর দেওয়া উচিত।
স্প্রিং বুটে RestTemplate
ব্যবহার করে HTTP GET, POST, PUT, DELETE রিকোয়েস্ট করার জন্য নিচের ধাপগুলো অনুসরণ করতে পারেন:
প্রথমে একটি RestTemplate
বীন কনফিগার করুন:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
GET
রিকোয়েস্টের মাধ্যমে ডেটা রিট্রিভ করতে getForObject
বা getForEntity
ব্যবহার করা হয়।
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String getApiResponse(String url) {
// GET Request
return restTemplate.getForObject(url, String.class);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Client {
@Autowired
private ApiService apiService;
public void getRequestExample() {
String response = apiService.getApiResponse("http://example.com/api/data");
System.out.println(response);
}
}
POST
রিকোয়েস্টের মাধ্যমে ডেটা পাঠাতে postForObject
বা postForEntity
ব্যবহার করা হয়।
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public String postApiResponse(String url, Object requestObject) {
// POST Request
ResponseEntity<String> response = restTemplate.postForEntity(url, requestObject, String.class);
return response.getBody();
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Client {
@Autowired
private ApiService apiService;
public void postRequestExample() {
String url = "http://example.com/api/create";
MyRequest requestObject = new MyRequest("value1", "value2");
String response = apiService.postApiResponse(url, requestObject);
System.out.println(response);
}
}
class MyRequest {
private String field1;
private String field2;
// Constructors, Getters, Setters
public MyRequest(String field1, String field2) {
this.field1 = field1;
this.field2 = field2;
}
// Getters and Setters...
}
PUT
রিকোয়েস্টের মাধ্যমে ডেটা আপডেট করতে put
ব্যবহার করা হয়।
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void updateResource(String url, Object requestObject) {
// PUT Request
restTemplate.put(url, requestObject);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Client {
@Autowired
private ApiService apiService;
public void putRequestExample() {
String url = "http://example.com/api/update/1";
MyRequest requestObject = new MyRequest("updatedValue1", "updatedValue2");
apiService.updateResource(url, requestObject);
System.out.println("Resource updated successfully.");
}
}
DELETE
রিকোয়েস্টের মাধ্যমে ডেটা মুছতে delete
ব্যবহার করা হয়।
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate;
public ApiService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void deleteResource(String url) {
// DELETE Request
restTemplate.delete(url);
}
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Client {
@Autowired
private ApiService apiService;
public void deleteRequestExample() {
String url = "http://example.com/api/delete/1";
apiService.deleteResource(url);
System.out.println("Resource deleted successfully.");
}
}
HTTP মেথড | RestTemplate মেথড |
---|---|
GET | getForObject , getForEntity |
POST | postForObject , postForEntity |
PUT | put |
DELETE | delete |
RestTemplate
এর সাথে Exception Handling এর জন্য try-catch
ব্লক বা Spring এর RestClientException
ব্যবহার করতে পারেন।HttpHeaders
এবং HttpEntity
ব্যবহার করে রিকোয়েস্টের সাথে হেডার যোগ করা সম্ভব।এইভাবে আপনি RestTemplate
ব্যবহার করে বিভিন্ন HTTP মেথডের রিকোয়েস্ট তৈরি এবং পরিচালনা করতে পারবেন।
Spring Boot Client ব্যবহার করে JSON বা XML ডেটা ফেচ এবং প্রসেস করা অত্যন্ত সহজ এবং সুবিধাজনক। Spring-এর RestTemplate এবং WebClient API সরঞ্জাম ব্যবহার করে এই কাজটি সম্পন্ন করা যায়। নিচে বিস্তারিতভাবে JSON এবং XML ডেটা হ্যান্ডলিং নিয়ে আলোচনা করা হলো।
Dependency যোগ করুন:
Maven প্রজেক্টের জন্য spring-boot-starter-web
ডিপেনডেন্সি যোগ করতে হবে।
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
JSON ডেটা ফেচ করার উদাহরণ:
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class SpringBootClientApplication implements CommandLineRunner {
private final RestTemplate restTemplate = new RestTemplate();
public static void main(String[] args) {
SpringApplication.run(SpringBootClientApplication.class, args);
}
@Override
public void run(String... args) {
String url = "https://jsonplaceholder.typicode.com/posts/1";
Post post = restTemplate.getForObject(url, Post.class);
System.out.println("Title: " + post.getTitle());
System.out.println("Body: " + post.getBody());
}
}
// POJO Class
class Post {
private Long id;
private String title;
private String body;
// Getters and Setters
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getBody() { return body; }
public void setBody(String body) { this.body = body; }
}
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.reactive.function.client.WebClient;
@SpringBootApplication
public class SpringBootClientApplication implements CommandLineRunner {
private final WebClient webClient = WebClient.create();
public static void main(String[] args) {
SpringApplication.run(SpringBootClientApplication.class, args);
}
@Override
public void run(String... args) {
String url = "https://jsonplaceholder.typicode.com/posts/1";
Post post = webClient.get()
.uri(url)
.retrieve()
.bodyToMono(Post.class)
.block();
System.out.println("Title: " + post.getTitle());
System.out.println("Body: " + post.getBody());
}
}
XML ডেটা প্রসেস করার জন্য spring-boot-starter-xml
বা jackson-dataformat-xml
ডিপেনডেন্সি ব্যবহার করতে হবে।
Dependency যোগ করুন:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
XML ডেটা ফেচ করার উদাহরণ:
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
@SpringBootApplication
public class SpringBootClientApplication implements CommandLineRunner {
private RestTemplate restTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringBootClientApplication.class, args);
}
@Override
public void run(String... args) {
restTemplate = createRestTemplate();
String url = "https://example.com/api/data.xml";
Item item = restTemplate.getForObject(url, Item.class);
System.out.println("Item Name: " + item.getName());
System.out.println("Item Description: " + item.getDescription());
}
private RestTemplate createRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
messageConverters.add(new MappingJackson2XmlHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);
return restTemplate;
}
}
@JacksonXmlRootElement(localName = "Item")
class Item {
private String name;
private String description;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.reactive.function.client.WebClient;
@SpringBootApplication
public class SpringBootClientApplication implements CommandLineRunner {
private final WebClient webClient = WebClient.create();
public static void main(String[] args) {
SpringApplication.run(SpringBootClientApplication.class, args);
}
@Override
public void run(String... args) {
String url = "https://example.com/api/data.xml";
Item item = webClient.get()
.uri(url)
.retrieve()
.bodyToMono(Item.class)
.block();
System.out.println("Item Name: " + item.getName());
System.out.println("Item Description: " + item.getDescription());
}
}
@JacksonXmlRootElement(localName = "Item")
class Item {
private String name;
private String description;
// Getters and Setters
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getDescription() { return description; }
public void setDescription(String description) { this.description = description; }
}
Jackson DataFormat
বা অন্য কোনো XML কনভার্টার ব্যবহার করতে হয়।আপনার প্রজেক্টের প্রয়োজন অনুযায়ী JSON বা XML ডেটা প্রসেস করতে এই উদাহরণগুলো অনুসরণ করতে পারেন।
নিচে স্প্রিং বুট ক্লায়েন্টে (Spring Boot Client) RestTemplate
ব্যবহার করে একটি উদাহরণ দেখানো হয়েছে:
Spring Initializr
-এ যান এবং Spring Boot Starter Web
ডিপেনডেন্সি যুক্ত করে একটি নতুন প্রজেক্ট তৈরি করুন। এরপরে প্রজেক্টে RestTemplate
ব্যবহার করা হবে।
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
RestTemplate ব্যবহারের জন্য একটি @Bean
কনফিগারেশন তৈরি করুন।
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class AppConfig {
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiClient {
private final RestTemplate restTemplate;
public ApiClient(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
// GET রিকোয়েস্ট
public String getData(String url) {
return restTemplate.getForObject(url, String.class);
}
// POST রিকোয়েস্ট
public String postData(String url, Object requestBody) {
return restTemplate.postForObject(url, requestBody, String.class);
}
}
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClientController {
private final ApiClient apiClient;
public ClientController(ApiClient apiClient) {
this.apiClient = apiClient;
}
// GET রিকোয়েস্ট
@GetMapping("/fetch-data")
public String fetchData() {
String url = "https://jsonplaceholder.typicode.com/posts/1"; // উদাহরণ API URL
return apiClient.getData(url);
}
// POST রিকোয়েস্ট
@PostMapping("/send-data")
public String sendData(@RequestBody Object requestBody) {
String url = "https://jsonplaceholder.typicode.com/posts"; // উদাহরণ API URL
return apiClient.postData(url, requestBody);
}
}
http://localhost:8080/fetch-data
https://jsonplaceholder.typicode.com/posts/1
থেকে ডেটা রিট্রিভ করবে।http://localhost:8080/send-data
Request Body (JSON):
{
"title": "foo",
"body": "bar",
"userId": 1
}
https://jsonplaceholder.typicode.com/posts
API-তে POST করবে এবং রেসপন্স ফিরিয়ে দেবে।RestTemplate ব্যবহার করার সময় try-catch
ব্লক দিয়ে এক্সসেপশন হ্যান্ডেল করুন:
public String getData(String url) {
try {
return restTemplate.getForObject(url, String.class);
} catch (Exception e) {
return "Error occurred: " + e.getMessage();
}
}
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}
{
"id": 101,
"title": "foo",
"body": "bar",
"userId": 1
}
তবে, নতুন প্রোজেক্টে স্প্রিং বুট ২.৪+ এ
WebClient
ব্যবহার করাই সুপারিশ করা হয়।RestTemplate
মূলতblocking
এবংsynchronous
কাজ করে।
Read more