需要多线程一个 unirest 请求并等待答案



我正在为多线程问题而苦苦挣扎。我需要通过 sendRESTRequest(jsonRequest) 发送请求,但我不想阻止 UI 线程,因此maskerPane.setVisible将被执行。

我可以使用JavaFX Task但是我必须在该线程中编写currentValueLabel.setText(等)。但是因为我重用了sendRESTRequest(jsonRequest)方法,所以我会用很多无用的行来炸毁我的代码。

是否可以在 antoher 线程上执行 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();
}

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

最新更新