Spring的RestTemplate是一個用于發送HTTP請求的模板類,可以很方便地與RESTful API進行交互。
首先,確保在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。