Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

android - HttpClient execute keeps giving ConnectTimeoutException

I have this very big bug in my application that I really can't seem to solve. Whenever I make a rest call via the following code:

  HttpGet request = new HttpGet(url + getParams());

  HttpParams httpParameters = new BasicHttpParams();
  HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
  HttpConnectionParams.setSoTimeout(httpParameters, 10000);

  DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);

  httpClient.execute(request);

I get the error in DDMS:

07-15 11:22:47.448: WARN/System.err(973): org.apache.http.conn.ConnectTimeoutException: Connect to (some ip-address) timed out

But sometimes the code works perfect and I receive my data as it should. I also tested the rest server call via a normal webbrowser on my computer and that always gives back my data within 100ms. So what am I doing wrong? I also tested it on another device, but that gives me the same problem. I would be SO glad if somebody could solve my problem :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The problem is the DefaultHttpClient. Are you using it asynchronously? Since the DefaultHttpClient is not thread-safe, using it in an asynchronous environment might cause a problem. I've had this problem before when my activity started multiple Http connection at the same time and i ended up changing it to use HttpURLConnection. You can refer to this site: http://www.vogella.de/articles/AndroidNetworking/article.html


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...