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

时间:2019-02-01 16:43:07

标签: java multithreading javafx unirest

我在解决多线程问题。我需要通过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();
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

现在我通过

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

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