You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SpringBoot中如何从外部Rest API获取Bearer Token并用于接口授权?

在SpringBoot中调用外部Rest API获取Bearer Token的问题解决

问题背景

之前用Spring Security做自研Rest API的认证,现在需要调用外部API获取Bearer Token,再用这个Token调用创建客户接口,但获取Token时触发错误:org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported。

外部API详情

认证接口(获取Token)

路径: https://qa2.sunbasedata.com/sunbase/portal/api/assignment_auth.jsp
请求方法: POST
请求体:
{
"login_id" : "test@sunbasedata.com",
"password" :"Test@123"
}

创建新客户接口

路径: https://qa2.sunbasedata.com/sunbase/portal/api/assignment.jsp
请求方法: POST
请求参数:
cmd : create
请求头:
Authorization: Bearer token_recieved_in_authentication_API_call
请求体:
 {
"first_name": "Jane",
"last_name": "Doe",
"street": "Elvnu Street",
"address": "H no 2 ",
"city": "Delhi",
"state": "Delhi",
"email": "sam@gmail.com",
"phone": "12345678"
}
  • 必填字段:first_name、last_name
  • 成功响应:201状态码,返回"Successfully Created"

错误原因

错误提示明确:调用认证接口时误用了GET方法,但该接口仅支持POST请求。

解决方案

1. 修正请求方法,用POST调用认证接口

下面提供SpringBoot中两种常用HTTP客户端的实现示例:

RestTemplate实现

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

// 注入提前配置好的RestTemplate Bean
@Autowired
private RestTemplate restTemplate;

public String fetchBearerToken() {
    String authEndpoint = "https://qa2.sunbasedata.com/sunbase/portal/api/assignment_auth.jsp";
    
    // 设置请求头为JSON格式
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    
    // 构造登录请求体
    Map<String, String> loginPayload = new HashMap<>();
    loginPayload.put("login_id", "test@sunbasedata.com");
    loginPayload.put("password", "Test@123");
    
    HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(loginPayload, headers);
    
    // 发送POST请求并接收响应
    ResponseEntity<String> response = restTemplate.postForEntity(authEndpoint, requestEntity, String.class);
    
    // 解析响应获取Token(假设响应体包含access_token字段)
    ObjectMapper objectMapper = new ObjectMapper();
    try {
        JsonNode responseBody = objectMapper.readTree(response.getBody());
        return responseBody.get("access_token").asText();
    } catch (Exception e) {
        throw new RuntimeException("解析Token失败", e);
    }
}

WebClient实现(推荐Spring WebFlux场景)

import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.databind.JsonNode;
import reactor.core.publisher.Mono;
import java.util.Map;

// 注入提前配置好的WebClient Bean
@Autowired
private WebClient webClient;

public Mono<String> fetchBearerToken() {
    return webClient.post()
            .uri("https://qa2.sunbasedata.com/sunbase/portal/api/assignment_auth.jsp")
            .contentType(MediaType.APPLICATION_JSON)
            .bodyValue(Map.of("login_id", "test@sunbasedata.com", "password", "Test@123"))
            .retrieve()
            .bodyToMono(JsonNode.class)
            .map(jsonNode -> jsonNode.get("access_token").asText());
}

2. 携带Token调用创建客户接口

拿到Token后,调用创建客户接口时需在请求头中添加Authorization: Bearer {token},示例(RestTemplate版本):

public void createCustomer(String bearerToken) {
    String createCustomerEndpoint = "https://qa2.sunbasedata.com/sunbase/portal/api/assignment.jsp?cmd=create";
    
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    headers.set("Authorization", "Bearer " + bearerToken);
    
    Map<String, Object> customerPayload = new HashMap<>();
    customerPayload.put("first_name", "Jane");
    customerPayload.put("last_name", "Doe");
    customerPayload.put("street", "Elvnu Street");
    customerPayload.put("address", "H no 2 ");
    customerPayload.put("city", "Delhi");
    customerPayload.put("state", "Delhi");
    customerPayload.put("email", "sam@gmail.com");
    customerPayload.put("phone", "12345678");
    
    HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(customerPayload, headers);
    restTemplate.postForEntity(createCustomerEndpoint, requestEntity, String.class);
}

注意事项

  • 确保RestTemplate/WebClient的Bean配置正确,避免实例化异常
  • 处理网络超时、响应解析失败等异常场景
  • 不要硬编码登录凭证,建议通过application.properties/yml配置注入

内容的提问来源于stack exchange,提问作者P I Y U S H D A S I L A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 00:06:31