我已经设置了连接超时和读取超时,但它们仍被忽略,请求永远保持不变。如何设置超时,以便在达到超时时取消请求? 这是我的代码段,感谢您的帮助。
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();
}
}
答案 0 :(得分:0)
我不确定这是否是最佳选择,我所做的是设置一个Timer,我曾经在HttpURLConnection上断开连接时间。到目前为止似乎工作正常。如果有人能够指出这种方法的缺点并提出更好的方法,我将不胜感激。