Ошибка запроса к API из Jenkins

Написал API через java HttpServer

Класс с обработкой запроса:

public class GetRequestAndroidDevices implements HttpHandler {

    @Override
    public void handle(HttpExchange exchange) {
        String listDevices;
        if (exchange.getRequestMethod().equalsIgnoreCase("GET")) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                String pathSelenoidConfigFile = System.getProperty("user.home") + SELENOID_ANDROID_PATH + "/config/devices.json";
                ConfigSelenoidAndroid configSelenoidAndroid = mapper.readValue(new File(pathSelenoidConfigFile), ConfigSelenoidAndroid.class);
                if (configSelenoidAndroid == null) {
                    throw new Exception("ConfigSelenoidAndroid is null");
                }
                List<String> devices = new ArrayList<>();
                Map<String, ConfigSelenoidAndroid.Android.Version> mapDevices = configSelenoidAndroid.android().versions();
                for (Map.Entry<String, ConfigSelenoidAndroid.Android.Version> androidDevice : mapDevices.entrySet()) {
                    devices.add(androidDevice.getKey());
                }
                listDevices = mapper.writeValueAsString(devices);
                System.out.println(listDevices);
                exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
            } catch (Exception e) {
                listDevices = "{\"error\": \"Ошибка чтения файла: " + e.getMessage() + "\"}";
                exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8");
                System.out.println("Ошибка: " + e.getMessage());
                e.printStackTrace();
            }
            successRequest(exchange, listDevices);
        } else {
            wrongMethodRestApi(exchange);
        }
    }
}

Класс с созданием ручки:

public class ServerSelenoidAndroidApiHelper {

    public interface AssociateEndpoint {
        void associate(String endpoint, HttpHandler handler);
    }

    public static void initializeSelenoidAndroidEndpoints(AssociateEndpoint endpointContext) {
        endpointContext.associate(SELENOID_ANDROID_DEVICES_ENDPOINT, new GetRequestAndroidDevices());
    }
}

И старт сервера:

public class ServerSelenoidApi {
    public static void main(String[] params) {
        String platform = params[0];
        System.out.println("Запущено с платформой: " + platform);
        if (android.toString().equals(platform)) {
            final ServerSelenoidAndroidApi serverSelenoidAndroidApi = new ServerSelenoidAndroidApi();
            serverSelenoidAndroidApi.startServerAndroid();
        } else if (ios.toString().equals(platform)) {
            final ServerSelenoidIosApi serverSelenoidIosApi = new ServerSelenoidIosApi();
            serverSelenoidIosApi.startServerIos();
        } else {
            System.err.printf("Wrong platform %s...%n", platform);
        }
    }
}

В Jenkins Pipeline есть функция для вызова этой API:

String getRequest(String url) {
    try {
        def response = sh(returnStdout: true, script: "curl -s -w '%{http_code}' ${url}").trim()
        def statusCode = response.tokenize("\n").getAt(-1)
        def responseBody = response.tokenize("\n").getAt(0..-2).join("\n")
        if (statusCode == "200") {
            def json = new groovy.json.JsonSlurper()
            def responseCheck = json.parseText(responseBody)
            return responseCheck
        }
    } catch (Exception e) {
        println "Ошибка обработки списка девайсов. Записываем захардкоженные значения. " + e
    }
    return null
}

Но при запуске джобы получаю такую ошибку при запросе:

13:06:55  + curl -s -w %{http_code} http://server-selenoid:7777/api/devices
[Pipeline] echo
13:06:55  Ошибка обработки списка девайсов. Записываем захардкоженные значения. java.lang.IndexOutOfBoundsException: fromIndex = -1

Хотя при запросе из Postman или консоли получаю корректный ответ. Почему в Jenkins на запрос выдает ошибку? Успешный запрос из Postman


Ответы (1 шт):

Автор решения: pbezpal

Разобрался. Вот так работает

String getRequestAndroid(String url) {
    try {
        def response = sh(returnStdout: true, script: "curl -s -w '%{http_code}' ${url}").trim()
        def matcher = response =~ /(.*)\d{3}$/
        if (matcher.find()) {
            def responseBody = matcher.group(1).trim()
            def statusCode = response.substring(response.length() - 3)
            if (statusCode == "200") {
                def json = new groovy.json.JsonSlurper()
                def responseCheck = json.parseText(responseBody)
                return responseCheck
            }
        }
    } catch (Exception e) {
        println "Ошибка обработки списка девайсов. Записываем захардкоженные значения. " + e
    }
    return null
}
→ Ссылка