Нужно многопоточность самого разового запроса и дождаться ответа - PullRequest
0 голосов
/ 01 февраля 2019

Я немного борюсь с многопоточностью.Мне нужно отправить запрос через sendRESTRequest(jsonRequest), но я не хочу блокировать поток пользовательского интерфейса, чтобы выполнить maskerPane.setVisible.

Я мог бы использовать JavaFX Task, но тогда мне нужно кодироватьмой currentValueLabel.setText (и т. д.) в этой теме.Но поскольку я повторно использую метод sendRESTRequest(jsonRequest), я взорву свой код множеством бесполезных строк.

Возможно ли выполнить sendRESTRequest в другом потоке, дождитесь результата Unirest.postи использовать возвращенный HttpResponse jsonResponse для дальнейшей обработки?

В настоящее время я использую этот код:

@FXML
protected void searchButtonAction() {
    maskerPane.setVisible(true);

    cardNumber = cardNumberTextField.getText();

    JSONObject jsonRequest = new JSONObject()
    .put("id", cardNumber)
    .put("trans", 20);


            //
            // How to put this asynchronus, but wait for the answer before continuing to System.out.println(loyaltyResponse.toString());
            //
    JSONObject loyaltyResponse = sendRESTRequest(jsonRequest);
            //
            //
            //

    System.out.println(loyaltyResponse.toString());

    currentValueLabel.setText(loyaltyResponse.getString("amount").replace(".", ",") + " Currency");
    maximumValueLabel.setText(loyaltyResponse.getString("balanceMax").replace(".", ",") + " Currency");

    maskerPane.setVisible(false);
}

private JSONObject sendRESTRequest(JSONObject jsonRequest) {
    HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest.post("http://myurl/")
        .header("accept", "application/json")
        .body(jsonRequest)
        .asJson();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return jsonResponse.getBody().getObject();
}

Спасибо за вашу помощь!

1 Ответ

0 голосов
/ 02 февраля 2019

Теперь я решил через

@FXML
protected void searchButtonAction() {
    maskerPane.setVisible(true);

    cardNumber = cardNumberTextField.getText();

    JSONObject jsonRequest = new JSONObject()
    .put("id", cardNumber)
    .put("trans", 20);
    Task<JSONObject> jsonRequestTask = new Task<JSONObject>() {
        @Override
        public JSONObject call() {
            return sendRESTRequest(jsonRequest);
        }
    };

    jsonRequestTask.setOnSucceeded(event -> {
        JSONObject loyaltyResponse = jsonRequestTask.getValue();

        currentValueLabel.setText(loyaltyResponse.getString("amount").replace(".", ",") + " Currency");
        maximumValueLabel.setText(loyaltyResponse.getString("balanceMax").replace(".", ",") + " Currency");

        maskerPane.setVisible(false);
    }

    jsonRequestTask.setOnFailed(event -> {
        maskerPane.setVisible(false);
    });

    new Thread(jsonRequestTask).start();
}

private JSONObject sendRESTRequest(JSONObject jsonRequest) {
    HttpResponse<JsonNode> jsonResponse = null;
    try {
        jsonResponse = Unirest.post("http://myurl/")
        .header("accept", "application/json")
        .body(jsonRequest)
        .asJson();
    } catch (UnirestException e) {
        e.printStackTrace();
    }

    return jsonResponse.getBody().getObject();
}

Работает нормально.Спасибо за вашу помощь.

...