Esempio di utilizzo della classe HttpURLConnection
Ecco parte di una funzione che uso per collegarmi ad una applicazione web tramite java, e le classi URL e HttpUTLConnection:
private String doURLConnection(String s) {
String result = "";
try {
URL smsHome = new URL (s );
HttpURLConnection huc = ( HttpURLConnection ) smsHome.openConnection ( ) ;
huc.setRequestMethod ( "GET" ) ;
huc.connect ( ) ;
int code = huc.getResponseCode ( ) ;
log.scrivi("Codice di ritorno: " + code);
if ( code == HttpURLConnection.HTTP_OK ) {
BufferedReader in = new BufferedReader( new InputStreamReader (
huc.getInputStream()));
log.scrivi("Stream da leggere: " + in.toString());
String inputLine;
while ( (inputLine=in.readLine())!=null) {
log.scrivi(" InputLine: " + inputLine);
}
in.close();
result = "200";
}else {
log.scrivi("Impossibile collegarsi: " + code);
result = "" + code;
}
huc.disconnect ( ) ;
} catch (MalformedURLException e) {
log.scrivi("MalformedURLException: " + e);
result = "300";
} catch (IOException e ) {
log.scrivi("IOException: " + e);
} catch (Exception e) {
log.scrivi("Eccezione Exception: " + e);
}
return result;
}
Leave a Reply