-1

I'd like to read contents of a textfile and display these in a JavaFX Scene Builder text area. I know how to do using a simple textfile but I must do it for an external textfile (means located on a server with HTTPS protocol).
I wrote the following snippet to check whether the file is available or not. That works but I must admit I'm stuck for the next step.. How could I parse and display the content of the file into the uiEtat text area component ?

try {
HttpsURLConnection.setFollowRedirects(false);
HttpsURLConnection con =
   (HttpsURLConnection) new URL("https://URL/file.txt").openConnection();
con.setRequestMethod("HEAD");
if (con.getResponseCode() == HttpsURLConnection.HTTP_OK){
    uiEtat.setText(); // here we fill the label with contents of file.txt
}
else
    uiEtat.setText("No content");
}

Any help would be greatly appreciated, thank you.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
Julien
  • 45
  • 1
  • 3
  • 15
  • 2
    Don't set the request method to `HEAD`, and call `getContent()`.... – James_D Jun 22 '21 at 15:31
  • it's unrelated to fx: first learn how to get the content (see @James_D), then apply what you learned to fill a control in fx. When stuck, come back with a [mcve] demonstrating what's not working as expected – kleopatra Jun 22 '21 at 15:36
  • 1
    I havent tried reading a file from a server, but i believe this should be very helpful to your case. https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests so it might be getContent() as mentioned above, and using inputstream and scanner to retrieve response – YHStan Jun 22 '21 at 16:05
  • With your explanations I tried to go further and finally wrote some lines that work pretty well (see my answer below). Thanks you very much for your answers, it helped ! – Julien Jun 23 '21 at 09:41

1 Answers1

0

Here is the snippet display the content of a text file with HTTPS protocol :

try {
    URL textFile = new URL("https://URLtextFile.txt");
    HttpsURLConnection con = (HttpsURLConnection) textFile.openConnection();
    con.setRequestMethod("GET");
    BufferedReader in = new BufferedReader(new InputStreamReader(
        con.getInputStream()));
    String inputLine;
    if (con.getResponseCode() == HttpsURLConnection.HTTP_OK){
        while ((inputLine = in.readLine()) != null) 
            uiEtat.setText(inputLine);
            in.close();
    }
}
catch (Exception e) {
    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String exceptionAsString = sw.toString();
    String errMessage = "Error being checked";
    uiEtat.setText(errMessage + "\n" + exceptionAsString);

 }
Julien
  • 45
  • 1
  • 3
  • 15