java.net.socketexception: The operation timed out problem in android?

前端 未结 2 1570
轮回少年
轮回少年 2020-12-11 06:24

In my application i wrote code for connecting to the URL like below

InputStream inputStream = new URL(url).openStream();    

i got the erro

2条回答
  •  醉话见心
    2020-12-11 07:13

    This is happening because some times your server is taking too long to respond. Actually this could also happening due to a slow network, so you don't have full control over it. If you were using HttpClient, you could increase the timeout period:

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, WAIT_RESPONSE_TIMEOUT);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);
    
    client = new DefaultHttpClient(httpParameters);
    

    CONNECTION_TIMEOUT is the time to wait for a connection to establish. WAIT_RESPONSE_TIMEOUT is the time to wait for data to be received - in your case this is what you need to increase.

    Bottom line:

    • Stop using URL and start using HttpClient now.
    • The situation you are describing is a very common one in a production application and you need to cater for it. Increasing the timeout won't always help, as your application will appear to halt when there is a slow network. You could add a retry mechanism or inform the user that the request has failed and ask him to try again.

提交回复
热议问题