英文:
RESTful API Authentication from JavaFX Desktop Client Application
问题
我目前正在开发一个使用JavaFX + FXML编写的桌面应用程序,我需要连接到一个我用NodeJS编写的远程RESTful API。我一直在尝试寻找一个更新的参考资料,适用于JDK 11及以上版本,但看起来大多数我找到的好的参考资料要么是关于Spring的,要么是至少3年前编写的。
有人能指点我正确的方向吗?谢谢。
英文:
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.
答案1
得分: 1
这是我到目前为止想出的。与我习惯使用的AJAX和Axios相比,它感觉原始而啰嗦,但仍然能够工作:
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();
// 在这里进行更多处理...
} catch (IOException e) {
Alert a = new Alert(AlertType.ERROR);
a.setContentText("登录:无法连接到服务器。检查您的连接,或稍后再试。要报告此错误,请联系 m@jhourlad.com。");
a.show();
} finally {
httpclient.close();
}
}
英文:
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 m@jhourlad.com.");
a.show();
} finally {
httpclient.close();
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论