YYour NameAccount Kit
c647687bAdd on Jun 10History
/*
 * Copyright (c) 2026 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.huawei.accountkit.credential;

import com.huawei.accountkit.credential.req.GetUserCredentialReq;
import com.huawei.accountkit.credential.resp.GetUserCredentialResp;
import com.huawei.accountkit.util.CallUtils;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 获取用户级凭证
 *
 * @author accountkit
 * @since 2026-04-14
 */
public class GetUserCredentialService {
    private static final String URL = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";

    /**
     * 调用华为账号服务器获取用户级凭证
     * 
     * @param req ObtainUserCredentialReq
     * @return ObtainUserCredentialResp
     * @throws IOException IOException
     */
    public static GetUserCredentialResp call(GetUserCredentialReq req) throws IOException {
        HttpPost httpPost = new HttpPost(URL);
        List<NameValuePair> request = new ArrayList<>();
        request.add(new BasicNameValuePair("grant_type", req.getGrantType()));
        request.add(new BasicNameValuePair("client_id", req.getClientId()));
        request.add(new BasicNameValuePair("client_secret", req.getClientSecret()));
        request.add(new BasicNameValuePair("code", req.getCode()));
        request.add(new BasicNameValuePair("supportAlg", req.getSupportAlg()));
        httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        httpPost.setEntity(new UrlEncodedFormEntity(request));

        // 如需要自定义异常处理请使用api CallUtils#remoteCall(HttpUriRequest, BiFunction<CloseableHttpResponse,String,E>)
        String res = CallUtils.remoteCallOAuth(httpPost);

        return CallUtils.parseObject(res, GetUserCredentialResp.class);
    }
}