Spring boot 发送get 请求

java 发送get请求

  • 发送工具类
  • 调用方法

发送工具类

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

public class RestUtil {
    private RestUtil() {
    }

    public static String doGetRequest(String url, HttpHeaders headers) {

        RestTemplate client = new RestTemplate();
        HttpMethod method = HttpMethod.GET;
        HttpEntity<String> requestEntity = new HttpEntity<String>("parameters", headers);

        // 执行HTTP请求,将返回的结构使用String类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }
}

调用方法

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;


public class LabelStudioUtil {

    @Value("${label-studio.access-token}")
    private String accessToken;

    @Value("${label-studio.host}")
    private String host;
    
    private LabelStudioUtil() {
    }

   

    public String getProjectById(String projectId) {
        String url = this.host + "/api/projects/" + projectId;
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "Token " + this.accessToken);

        return RestUtil.doGetRequest(url, headers);
    }

}

你可能感兴趣的:(java,spring,boot)