Jhourlad Estrella
Jhourlad Estrella

Reputation: 3670

RESTful API Authentication from JavaFX Desktop Client Application

I'm currently developing a desktop application written in JavaFX + FXML and I need to connect to a remote RESTful API I wrote in NodeJS. I've been trying to find an updated reference catering to JDK 11 and up but it looks like most good references I find are either in Spring or were written at least 3 years ago.

Can anybody point me in the right direction? Thanks.

Upvotes: 0

Views: 949

Answers (1)

Jhourlad Estrella
Jhourlad Estrella

Reputation: 3670

This is what I have come up so far. It feels primitive and chatty compared to I am used to using AJAX and Axios but works nevertheless:

private void btnLoginClick() throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost("http://localhost:8000/api/auth");
    httpPost.addHeader("accept", "application/json");
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("email", username.getText()));
    params.add(new BasicNameValuePair("password", password.getText()));
    httpPost.setEntity(new UrlEncodedFormEntity(params));

    try {
        CloseableHttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        String data = EntityUtils.toString(entity);
        JSONObject json = new JSONObject(data);
        EntityUtils.consume(entity);
        response.close();
        // Do more processing here...

    } catch (IOException e) {
        Alert a = new Alert(AlertType.ERROR);
        a.setContentText("Login: Unable to connect to server. Check your connection or try at a later time. To report this error please contact [email protected].");
        a.show();
    } finally {
        httpclient.close();
    }
}

Upvotes: 1

Related Questions