DefaultHttpClient类Android中的超时

我创建了一个Android应用程序,我连接到远程服务器php文件以检索一些信息。 下面是代码。

这里我想添加连接超时,例如连接将在5秒内超时。

不知道怎么做。

ArrayList nameValuePairs = new ArrayList(); nameValuePairs.add(new BasicNameValuePair("name","test")); HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://mysite.com/test.php"); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); 

问候,

尚卡尔

使用DefaultHttpClientHttpConnectionParams ::

 final HttpParams httpParameters = yourHttpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000); HttpConnectionParams.setSoTimeout (httpParameters, socketTimeoutSec * 1000); 
 final HttpParams httpParameters = yourHttpClient.getParams(); HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000); HttpConnectionParams.setSoTimeout (httpParameters, socketTimeoutSec * 1000); 

如果这不起作用(如我的情况)。 试试这对我有用( 链接 )

 HttpGet httpGet = new HttpGet(url); HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in milliseconds until a connection is established. // The default value is zero, that means the timeout is not used. int timeoutConnection = 3000; HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. int timeoutSocket = 5000; HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);