SView Help Center
English (US)

获取AccessToken(客户端模式)

Author: sviewngts Last Updated: 2026-08-25 16:25
接口名 POST: /auth/oauth2/token
入参:(body传值) application/x-www-form-urlencoded
是否必传 默认值 描述 备注
grant_type 是 client_credentials   固定值:client_credentials
scope 是 server   固定值:server
入参:(Header传值)
Authorization 是 - 客户端标识 格式:Basic base64(clientId:clientSecret)
Content-Type 是 - Content-Type application/x-www-form-urlencoded
回参示例:(application/json)

 

{
    "access_token": "462174fc-e67a-4674-b5d4-d03868057bf3",
    "scope": "server",
    "token_type": "Bearer",
    "expires_in": 43199 //token有效期(秒)
}
 
package com.hoteam.sview.demo;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OAuth2TokenDemo {

    private static final String TOKEN_URL = "http://your-host/auth/oauth2/token";
    /** 设备唯一标识 ,可联系授权人员获取 */
    private static final String CLIENT_ID     = "your_client_id";
    private static final String CLIENT_SECRET = "your_client_secret";

    public static String getAccessToken() {
        String basicAuth = "Basic " + Base64.encode(
                (CLIENT_ID + ":" + CLIENT_SECRET).getBytes(CharsetUtil.CHARSET_UTF_8));

        HttpRequest request = HttpRequest.post(TOKEN_URL)
                .header(Header.AUTHORIZATION, basicAuth)
                .header(Header.CONTENT_TYPE, ContentType.FORM_URLENCODED.getValue())
                .form("grant_type", "client_credentials")
                .form("scope", "server")
                .timeout(10_000);

        // 追加公共 Header
        CommonHeaderUtil.withCommonHeaders(request);

        try (HttpResponse response = request.execute()) {
            int status = response.getStatus();
            String body = response.body();
            log.info("获取 AccessToken 响应:status={}, body={}", status, body);

            if (status == HttpStatus.HTTP_UNAUTHORIZED) {
                log.warn("获取 AccessToken 认证失败(401),请检查 clientId / clientSecret,body={}", body);
                return null;
            }
            if (!response.isOk() || StrUtil.isBlank(body)) {
                log.warn("获取 AccessToken 失败:status={}, body={}", status, body);
                return null;
            }

            JSONObject json = JSONUtil.parseObj(body);
            String accessToken = json.getStr("access_token");
            if (StrUtil.isBlank(accessToken)) {
                log.warn("响应中未获取到 access_token,body={}", body);
                return null;
            }
            return accessToken;
        } catch (Exception e) {
            log.error("调用 OAuth2 Token 接口异常", e);
            return null;
        }
    }
}