1
我設置了連接超時和讀取超時但仍然被忽略,請求只是永遠保持。如何設置超時,以便在達到超時時請求被取消? 這是我的代碼片斷,感謝您的幫助。HttpURLConnection連接超時不起作用
urlConnection = (HttpURLConnection) saveURL.openConnection();
// is output buffer writer
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "text/html");
urlConnection.setRequestProperty("userid", id);
urlConnection.setConnectTimeout(3000);
urlConnection.setReadTimeout(3000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(jsonString);
writer.flush();
// json data
writer.close();
is = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String inputLine = "";
while ((inputLine = br.readLine()) != null) {
sb.append(inputLine);
}
int responseCode = urlConnection.getResponseCode();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SocketTimeoutException soce) {
// TODO Auto-generated catch block
soce.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != urlConnection)
urlConnection.disconnect();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
你怎麼知道它不工作? –
因爲我設置了10秒的超時時間並對其進行計時。它持續了2分鐘以上,終於成功了。但問題是我已經看到它持續超過5分鐘,仍然沒有超時。我需要正常處理超時,以便用戶可以在網速更好時再次嘗試上傳。 –
我只是說你似乎沒有回報什麼? –