UrlConnection e HttpUrlConnection

In una applicazione utilizzavo il seguente codice per raggiungere un URL (un’applicazione tomcat);
URL smsHome = new URL (s );

URLConnection smsConnection = smsHome.openConnection();
smsConnection.setConnectTimeout(600000);
smsConnection.setReadTimeout(600000);BufferedReader in = new BufferedReader( new InputStreamReader (
smsConnection.getInputStream()));

String inputLine;
while ( (inputLine=in.readLine())!=null) {
log.scrivi(" InputLine: " + inputLine);
}
in.close();

Questa soluzione, sotto la versione 1.6 mi ha dato dei problemi, di java.net.ConnectException: Connection timed out: connect, che a dir la verità  tutt’ora non riesco a spiegare.

Per cercare di risolvere questo problema ho modificato il codice, in questo modo:

URL smsHome = new URL (s );HttpURLConnection huc = ( HttpURLConnection ) smsHome.openConnection ( ) ;
huc.setRequestMethod ( "GET" ) ;
huc.connect ( ) ;
int code = huc.getResponseCode ( ) ;

BufferedReader in = new BufferedReader( new InputStreamReader (huc.getInputStream()));

String inputLine;
while ( (inputLine=in.readLine())!=null) {
log.scrivi(" InputLine: " + inputLine);
}
in.close();
huc.disconnect ( ) ;

Il problema sembra sparito, ma non so perchè. In ogni caso, nel secondo frammento di codice manca la gestione del code di ritorno huc.getResponseCode (). Un esempio può essere:
if ( code == HttpURLConnection.HTTP_OK ) {
... fai quello che devi fare...
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>