Как создать URL-адрес API в Springboot - PullRequest
1 голос
/ 05 августа 2020

Я новичок в SpringBoot и пытаюсь выполнить требование. Мне просто нужно вызвать API, передав client_id, secret и grant type, это сгенерирует токен, как показано на скриншоте ниже. Мне просто нужно получить это значение токена.

введите описание изображения здесь

Я создал POJO на основе ответа API.

TokenReqPOJO. java:

public class TokenReqPOJO {

    private String access_token;
    private String token_type;
    private int expires_in;

    @Override
    public String toString() {
        return "ClassPojo [access_token = " + access_token + ", token_type = " + token_type + ", expires_in = "
                + expires_in + "]";
    }

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    public String getToken_type() {
        return token_type;
    }

    public void setToken_type(String token_type) {
        this.token_type = token_type;
    }

    public int getExpires_in() {
        return expires_in;
    }

    public void setExpires_in(int expires_in) {
        this.expires_in = expires_in;
    }
}

POJO выше поможет получить токен из тела ответа.

Теперь у меня два вопроса:

  • Как построить URI в нужном формате? Как указано на скриншоте ниже, URI будет состоять из 3 частей: конечная точка + ресурс + параметры
  • Как сопоставить код ответа и получить значения из тела ответа?

I начали с кода ниже, но не смогли продолжить.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;


@RestController
public class TokenAPI {
    
    private static final Logger logger = LogManager.getLogger(TokenAPI.class);

    @Value("${TOKEN_CLIENT_SEC_PARAM_VALUE}")
    private String TOKEN_CLIENT_SECRET_PARAM_VALUE;

    @Value("${TOKEN_CLIENT_ID_PARAM_VALUE}")
    private String TOKEN_CLIENT_ID_PARAM_VALUE;

    @Value("${TOKEN_GRANT_TYPE_PARAM_VALUE}")
    private String TOKEN_GRANT_TYPE_PARAM_VALUE;

    @Value("${RetryCount}")
    private int RetryCount;

    @Value("${TOKEN_GEN_API_URL}")
    private String TOKEN_GEN_API_URL;
    
    
    @PostMapping("<?>") //HOW TO PASS FULL URL
    public void getAuthToken( ) {
     
        // how to read response , returned by API
        // will RestTemplate help?
        

        
    }

}

1 Ответ

0 голосов
/ 05 августа 2020

Вам следует попробовать использовать библиотеку okhttp, как описано на веб-сайте Baeldung

Например:

import okhttp3.*;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

@Service("tokenService")
public class TokenServiceImpl implements ITokenService {

    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");

    private OkHttpClient client;

    private String url;

    private String login;

    private String bindings;

    private final String username;

    private final String password;
    @Value("${heatzy.api.appid}")
    private String appid;

    public TokenServiceImpl(@Value("${api.username}") String username,
                            @Value("${api.password}") String password,
                            @Value("${api.url}") String url,
                            @Value("${api.url.login}") String login,
                            @Value("${api.url.devices}") String bindings) {
        List<Protocol> protocols = new ArrayList<>();
        protocols.add(Protocol.HTTP_1_1);
        protocols.add(Protocol.HTTP_2);
        this.username = username;
        this.password = password;
        this.url = url;
        this.login = login;
        this.bindings = bindings;

        this.client = new OkHttpClient.Builder()
                .readTimeout(5, TimeUnit.SECONDS)
                .callTimeout(5, TimeUnit.SECONDS)
                .followRedirects(true)
                .protocols(protocols)
                .build();
    }

    public String getToken() {
        JSONObject json = new JSONObject();
        json.put("username", username);
        json.put("password", password);

        RequestBody body = RequestBody.create(json.toString(), JSON);
        Request req = new Request.Builder()
                .url(url + "/" + login)
                .addHeader("Content-Type", "application/json")
                .addHeader("X-Gizwits-Application-Id", appid)
                .post(body)
                .build();

        Call call = client.newCall(req);
        try {
            Response reponse = call.execute();

            System.out.println(reponse.code());
            String message = reponse.body().string();
            reponse.close();

            return message;

        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

}
...