HttpURLConnection错误:java.net.SocketTimeoutException:连接超时

我正在使用这样的简单urlconnection:

url = URL+"getClient&uid="+cl_id; URL url = new URL(this.url); Log.d("Set++","get_t URL: "+ url); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 

它工作正常,但有时我得到这个错误:

  error: java.net.SocketTimeoutException: Connection timed out 

可能是什么原因? 我只有4个客户……所以我不认为服务器超载连接。

代码:

  try { URL = Settings.BASE_URL + "_interface.php?" + "key=" + Settings.KEY +"&app_naam="+Settings.APP_NAAM+ "&action=check&setTime="+c; URL url = new URL(URL); if(D)Log.e("ChekTreadAanvr+url", URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); BufferedReader rd = new BufferedReader( new InputStreamReader(conn.getInputStream())); String response; if ((response = rd.readLine()) != null) { rd.close(); } if(D) Log.d("WebSaveThread+","DATARESIEVED: "+response); return response; } catch (MalformedURLException e) { if(D)Log.d("ERR","server chekc failure ++ "); return success = false; } catch (IOException ioex) { if(D)Log.e("ERR", "error: " + ioex.getMessage(), ioex); success = false; } return Boolean.toString(success); 

您的Internet连接速度可能很弱。 您可以使用以下方法增加超时间隔。

 httpURLConnection.setConnectTimeout( 6 * 10 * 1000 ); // One Minute 

如果要连接到速度特别慢的服务器,则可以设置两个超时: setConnectTimeout()setReadTimeout() 。 名字是相当自我解释的。 例如:

  httpURLConnection.setConnectTimeout(60*1000); httpURLConnection.setReadTimeout(60*1000);