扫描二维码下载沐宇APP

沐宇

微信扫码使用沐宇小程序

沐宇

Spring鐨剅esttemplate鎬庝箞浣跨敤

扬州沐宇科技
2023-12-21 16:19:48
spring

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>

扫码添加客服微信