Inserimento codice relativo a java.net URL e HttpUrlConnection

This commit is contained in:
2023-03-10 15:47:15 +01:00
parent 75accbd36a
commit 89c209b9e9
19 changed files with 2079 additions and 6 deletions

View File

@@ -0,0 +1,65 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Main.java to edit this template
*/
package clienthttp;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ClientHttp {
private static String sitoUrl = "http://server.mirimatcode.eu/file";
private static URL risorsa;
private static HttpURLConnection connessione;
public static void main(String[] args) {
try {
/*
Download di un file mediante richiesta HTTP, se il file è un txt stampa a video il contenuto
altrimenti crea una copia del file in locale
*/
System.out.println("Mi appresto a scaricare il file di testo");
risorsa = new URL(sitoUrl);
connessione = (HttpURLConnection) risorsa.openConnection();
String content = connessione.getContentType() == null ? "application/unk" : connessione.getContentType();
System.out.println("Valore " + content);
//System.out.println("Content type restituito: " + content + "\n" + " Oggetto restituito: " + connessione.getContent().getClass().getName());
if(content.equals("text/plain")) {
BufferedReader buf = new BufferedReader(new InputStreamReader((InputStream) connessione.getContent()));
System.out.println("Frase: " + buf.readLine());
buf.close();
} else {
String estensione = content.split("/")[1];
FileOutputStream streamFile = new FileOutputStream("file_ricevuto." + estensione);
System.out.println("Estensione: " + estensione);
streamFile.write(((InputStream) connessione.getContent()).readAllBytes());
streamFile.flush();
streamFile.close();
}
} catch (MalformedURLException ex) {
System.out.println("Errore Malformed: " + ex.getMessage());
} catch (FileNotFoundException ex) {
System.out.println("Errore FileNotFound: " + ex.getMessage());
} catch (IOException ex) {
System.out.println("Errore IO: " + ex.getMessage());
}
}
}