DefaultHttpClient类Android中的超时

Bha*_*kar 11 android

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

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

知道如何做到这一点.

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
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); 
Run Code Online (Sandbox Code Playgroud)

问候,

尚卡尔

Shl*_*blu 31

使用HttpConnectionParams你的DefaultHttpClient::

final HttpParams httpParameters = yourHttpClient.getParams();

HttpConnectionParams.setConnectionTimeout(httpParameters, connectionTimeOutSec * 1000);
HttpConnectionParams.setSoTimeout        (httpParameters, socketTimeoutSec * 1000);
Run Code Online (Sandbox Code Playgroud)

  • 超时是好的,但是我们如何抓住时间(现在的代码只是在超时时无声地失败) (2认同)