как запросить другой API в качестве клиента в методе ServerResource в Restlet - PullRequest
0 голосов
/ 19 февраля 2020

Я создал API в рестлете 2.4.2 java все работает нормально. Я получаю эту ошибку, когда пытаюсь вызвать другой API-интерфейс в качестве клиента в моем файле ServerResource.

Вот мой вызывающий API-код в качестве кода клиента:

Client client = new Client(new Context(), Protocol.HTTPS);
client.getContext().getParameters().add("useForwardedForHeader","false");
ClientResource cr = new ClientResource("https://www.examples.com");
try{ 
cr.get(MediaType.APPLICATION_ALL).write(System.out); 
} catch(ResourceException | IOException e) { e.printStackTrace(); }

Ошибка, с которой я сталкиваюсь:

The protocol used by this request is not declared in the list of client connectors. (HTTPS/1.1). In case you are using an instance of the Component class, check its "clients" property.

Я пытался добавить библиотеку httpclient в pom.xml / maven, но безуспешно

<dependency>
    <groupId>org.restlet.jse</groupId>
    <artifactId>org.restlet.ext.httpclient</artifactId>
    <version>2.4.0</version>
</dependency>

1 Ответ

2 голосов
/ 23 февраля 2020

Ваша проблема заключается в том, что вам нужно настроить HTTPS-коннектор для вашего http-клиента рестлета.

Я сделал этот простой пример проекта для вас образец https сервер / клиент

В этом примере у вас есть образец сервера HTTPS с хранилищем ключей с самозаверяющим сертификатом (для целей тестирования) и клиент HTTPS с тем же настроенным хранилищем ключей / сертификатом.

Пример кода клиента:

private static final String url = "https://localhost:8443/";

public static void main(String[] args) {
    System.out.println("Sending HTTP GET request to " + url);
    // Add your HTTPS specifications
    String file = "keystore-dev.jks";
    String keystorePwd = "localhost";
    String keyPwd = "localhost";
    File keystoreFile = new File(file);

    if (keystoreFile.exists()) {
        Request request = new Request(Method.GET, url);
        System.setProperty("javax.net.ssl.trustStore", keystoreFile.getAbsolutePath());
        System.setProperty("javax.net.ssl.trustStorePassword", keystorePwd);
        System.setProperty("javax.net.ssl.keyStore", keystoreFile.getAbsolutePath());
        System.setProperty("javax.net.ssl.keyStorePassword", keystorePwd);

        Client client = new Client(new Context(), Protocol.HTTPS);
        client.getContext().getParameters().add("sslContextFactory",
                "org.restlet.engine.ssl.DefaultSslContextFactory");
        client.getContext().getParameters().add("keystoreType", "JKS");
        client.getContext().getParameters().add("keystorePath", keystoreFile.getAbsolutePath());
        client.getContext().getParameters().add("keystorePassword", keystorePwd);
        client.getContext().getParameters().add("keyPassword", keyPwd);

        Response resp = client.handle(request);

        System.out.println("Service response code: " + resp.getStatus());
        try {
            System.out.println("Service response body: " + resp.getEntity().getText());
        } catch (IOException e) {
            System.out.println("Error reading response");
        }

    } else {
        System.err.println("Error keystore not found");
    }

}

Клиент pom. xml зависимости:

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.github.arielcarrera</groupId>
    <artifactId>restlet-https-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>restlet-https-client</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <version.restlet>2.4.0</version.restlet>
        <version.junit>4.13</version.junit>
    </properties>

    <repositories>
        <repository>
            <id>maven-restlet</id>
            <name>Restlet repository</name>
            <url>https://maven.restlet.com</url>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>org.restlet.jse</groupId>
            <artifactId>org.restlet.ext.httpclient</artifactId>
            <version>${version.restlet}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${version.junit}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

Пример командной строки для создания тестового хранилища ключей:

keytool -genkey -alias localhost -keyalg RSA -keysize 2048 -keypass localhost -storepass localhost -keystore keystore-dev.jks

Для получения дополнительной информации читайте о Restlet - клиентские соединители и Restlet - HTTPS .

Вы можете использовать Сервер / Клиентские ресурсы тоже.

Надеюсь, это поможет.

...