需要多线程处理一个 unirest 请求并等待答复

Need to multithread a unirest request and wait for answer

我正在努力解决多线程问题。我需要通过 sendRESTRequest(jsonRequest) 发送请求,但我不想阻塞 UI 线程,因此 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();
}

感谢您的帮助!

现在我通过

解决了
@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();
}

工作正常。感谢您的帮助。