как сделать вызов API REST для метода, который принимает параметры - PullRequest
0 голосов
/ 15 января 2020

Я довольно новичок в совершении вызовов API. Мне дали класс java, который генерирует токен. Меня попросили создать веб-сервис, который выполняет вызовы API для метода SecurityUtil .calculateAuthorizationSignature (fields, clientId, clientSecret), используя эти параметры

вместо жесткого кодирования, как показано в классе ниже:

publi c class SecurityUtil {publi c stati c void main (String [] args) {

    String[] fields = new String[3];

// POC + 100 + 05QQAWQERQWHYTFDYUSwY

    fields[0] = "POC";
    fields[1] = "100";
    fields[2] = "05QQAWQERQWHYTFDYUSwY2";

    String clientId = "dfaaa525-704c-41f4-9d95-7983f9bee18d";
    String clientSecret = "6r9186uxrt031lw0diivck9noma1onfq";

    String signatureStr = new SecurityUtil()
            .calculateAuthorizationSignature(fields, clientId, clientSecret);

    System.out.println(signatureStr);
}

public String encodeBase64(String val) {
    return Base64.getEncoder().encodeToString(val.getBytes());
}

public String decodeBase64(String val) throws UnsupportedEncodingException {
    return new String(Base64.getDecoder().decode(val), "ASCII");
}

public String hmacSha256(String val, String key) {
    return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, key).hmacHex(val);
}

public String calculateAuthorizationSignature(String[] fields, String id, String secret) {
    StringBuilder sb = new StringBuilder();
    boolean addSeparator = false;
    for (String s : fields) {
        if (addSeparator) {
            sb.append("+");
        }
        sb.append(s);
        addSeparator = true;
    }

    String serverSignature = hmacSha256(sb.toString(), secret);
    String clientId = encodeBase64(id);

    Instant instant = Instant.now();
    Long timeStampMillis = instant.getEpochSecond();
    String timeStamp = encodeBase64(String.valueOf(timeStampMillis));

    String cipher = serverSignature + "." + timeStamp + "." + clientId;
    return encodeBase64(cipher);
}

}

я использую весеннюю загрузку, и мой файл pom показан ниже:

https://maven.apache.org/xsd/maven-4.0.0.xsd "> 4.0.0 org.springframework.boot spring-boot-starter-parent 2.2. 2.RELEASE com.abelinho.securityutil secutildemo 0.0.1-SNAPSHOT secutildemo Демонстрационный проект для Spring Boot

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>

    <dependency>
        <groupId>commons-codec</groupId>
        <artifactId>commons-codec</artifactId>
        </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

, и моя структура проекта показана ниже:

1

Пожалуйста, помогите. Спасибо, ребята!

1 Ответ

0 голосов
/ 15 января 2020

Для вызова API вам нужно использовать любой http-клиент, например RestTemplate или FeignClient, используя шаблон отдыха, который вы можете вызвать API,

  fields[0] = "POC";
  fields[1] = "100";
  fields[2] = "05QQAWQERQWHYTFDYUSwY2";

  String clientId = "dfaaa525-704c-41f4-9d95-7983f9bee18d";
  String clientSecret = "6r9186uxrt031lw0diivck9noma1onfq";

    public String copyAssests(String clientId , String clientSecret, String[] fields) {
        return restTemplate.exchange("url", HttpMethod.POST, getHttpEntity(request, null, appCode), String.class, fields).getBody();
    }

   private <T> HttpEntity<T> getHttpEntity(T t, String authorization, String appCode) {
        HttpHeaders headers = new HttpHeaders();
        headers.add("header", "value");
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        return new HttpEntity<>(t, headers);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...