SpringのRestTemplateはどのように使いますか?
SpringのRestTemplateは、RESTful APIと簡単にやり取りできるHTTPリクエストを送信するためのテンプレートクラスです。
最初に、pom.xmlファイルに以下の依存関係が追加されていることを確認してください。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
その後、RestTemplateをインジェクトしてコード内で使用します。
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class MyService {
private final RestTemplate restTemplate;
@Autowired
public MyService(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public void makeGetRequest() {
String url = "http://example.com/api/resource";
ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
System.out.println(response.getBody());
}
public void makePostRequest() {
String url = "http://example.com/api/resource";
String requestBody = "Hello, world!";
ResponseEntity<String> response = restTemplate.postForEntity(url, requestBody, String.class);
System.out.println(response.getBody());
}
public void makePutRequest() {
String url = "http://example.com/api/resource";
String requestBody = "Hello, world!";
restTemplate.put(url, requestBody);
}
public void makeDeleteRequest() {
String url = "http://example.com/api/resource";
restTemplate.delete(url);
}
}
上記の例では、RestTemplateインスタンスをインジェクションし、異なる方法でGET、POST、PUT、DELETEリクエストを送信しています。 getForEntity()メソッドはGETリクエストを送信して応答エンティティを返し、postForEntity()メソッドはPOSTリクエストを送信して応答エンティティを返します。 put()メソッドはPUTリクエストを送信し、delete()メソッドはDELETEリクエストを送信します。
これらのコードは単なる簡単な例ですので、自分の実際のニーズに応じてRestTemplateを使用してください。