Spring鐨剅esttemplate鎬庝箞浣跨敤
Spring鐨凴estTemplate鏄竴涓敤浜庡彂閫丠TTP璇锋眰鐨勬ā鏉跨被锛屽彲浠ュ緢鏂逛究鍦颁笌RESTful API杩涜浜や簰銆?/p>
棣栧厛锛岀‘淇濆湪pom.xml鏂囦欢涓坊鍔犱簡浠ヤ笅渚濊禆锛?/p>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
鐒跺悗锛屽湪浣犵殑浠g爜涓€氳繃娉ㄥ叆RestTemplate鏉ヤ娇鐢ㄥ畠锛?/p>
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);
}
}
鍦ㄤ笂闈㈢殑绀轰緥涓紝鎴戜滑娉ㄥ叆浜嗕竴涓猂estTemplate瀹炰緥锛屽苟閫氳繃涓嶅悓鐨勬柟娉曟潵鍙戦€丟ET銆丳OST銆丳UT鍜孌ELETE璇锋眰銆傚叾涓紝getForEntity()鏂规硶鐢ㄤ簬鍙戦€丟ET璇锋眰骞惰繑鍥炲搷搴斿疄浣擄紝postForEntity()鏂规硶鐢ㄤ簬鍙戦€丳OST璇锋眰骞惰繑鍥炲搷搴斿疄浣擄紝put()鏂规硶鐢ㄤ簬鍙戦€丳UT璇锋眰锛宒elete()鏂规硶鐢ㄤ簬鍙戦€丏ELETE璇锋眰銆?/p>
浠ヤ笂浠g爜鍙槸涓€涓畝鍗曠殑绀轰緥锛屼綘鍙互鏍规嵁鑷繁鐨勫疄闄呴渶姹傛潵浣跨敤RestTemplate銆?/p>
相关问答