5
Sto cercando di ottenere l'uso della funzione di setConnectTimeout come questa:HttpUrlConnection setConnectTimeout non funziona?
protected HttpURLConnection getConnection() throws SocketTimeoutException, IOException{
Log.d("HTTPRequest", address);
URL page = new URL(address);
HttpURLConnection connection = (HttpURLConnection) page.openConnection();
connection.setUseCaches(cacheResult);
connection.setConnectTimeout(3000);
connection.connect();
return connection;
}
e poi:
public String getTextData() throws InternetConnectionUnavailableException {
try{
HttpURLConnection conn = getConnection();
StringBuffer text = new StringBuffer();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
while (true) {
if((line = buff.readLine()) != null){
text.append(line);
}else{
break;
}
}
return (text.toString());
} catch (SocketTimeoutException socketTimeoutException) {
throw new InternetConnectionUnavailableException();
} catch (IOException ioException) {
throw new InternetConnectionUnavailableException();
}
}
Tuttavia, si arriva mai al "catch (SocketTimeoutException socketTimeoutException)" blocco. Cosa c'è di sbagliato qui.
P.S. Per il test ho creato una pagina che mette in pausa il mio server per 10 secondi.
Va bene! Sembra che funzioni, ma non con.setRequestMethod ("HEAD"); pasticciare qualcosa? – user1462299
Come supposto a causa di questa riga, non è stato possibile caricare i collegamenti normali. Ho semplicemente rimosso questo e aggiunto conn.connect(); Genera ora un'eccezione IOException dopo il timeout si esaurisce - non lo faccio se si tratta di IOException o qualsiasi altra cosa a meno che non funzioni – user1462299
Sembra che il timeout non funzioni se la rete è disconnessa a metà download. – NoBugs