Getting java.net.SocketTimeoutException: Connection timed out in android
Asked Answered
H

9

98

I'm developing an android application where I'm sending requests to the web server and parsing JSON objects. Frequently I'm getting java.net.SocketTimeoutException: Connection timed out exception while communicating with the server. Some times it will work perfectly without any problem. I know this same question has been asked in SO many times. But still, I didn't get any satisfying solution to this problem. I'm posting my logcat and app-server communication code below.

public JSONObject RequestWithHttpUrlConn(String _url, String param){

    HttpURLConnection con = null;
    URL url;
    String response = "";
    Scanner inStream = null;
    PrintWriter out = null;
    try {
        url = new URL(_url);
        con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        if(param != null){
            con.setFixedLengthStreamingMode(param.getBytes().length);
        }
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        out = new PrintWriter(con.getOutputStream());
        if(param != null){
            out.print(param);
        }
        out.flush();
        out.close();
        inStream = new Scanner(con.getInputStream());

        while(inStream.hasNextLine()){
            response+=(inStream.nextLine());
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally{
        if(con != null){
            con.disconnect();
        }if(inStream != null){
            inStream.close();
        }if(out != null){
            out.flush();
            out.close();
        }
    }
}

Logcat:

03-25 10:55:32.613: W/System.err(18868): java.net.SocketTimeoutException: Connection 
timed out
03-25 10:55:32.617: W/System.err(18868):at org.apache.harmony.luni.platform.OSNetworkSystem.connect(Native Method)
03-25 10:55:32.617: W/System.err(18868):at dalvik.system.BlockGuard
$WrappedNetworkSystem.connect(BlockGuard.java:357)
03-25 10:55:32.617: W/System.err(18868):at 
org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:204)
03-25 10:55:32.617: W/System.err(18868):at 
org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:437)
03-25 10:55:32.617: W/System.err(18868):at        java.net.Socket.connect(Socket.java:1002)
03-25 10:55:32.621: W/System.err(18868):at 
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>
(HttpConnection.java:75)
03-25 10:55:32.621: W/System.err(18868): at 
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection.<init>
(HttpConnection.java:48)03-25 10:55:32.624: W/System.err(18868):at 
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnection$Address.connect
(HttpConnection.java:322)03-25 10:55:32.624: W/System.err(18868):at 
org.apache.harmony.luni.internal.net.www.protocol.http.HttpConnectionPool.get
(HttpConnectionPool.java:89)03-25 10:55:32.628: W/System.err(18868):at 
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getHttpCon
nection(HttpURLConnectionImpl.java:285)
03-25 10:55:32.628: W/System.err(18868):at     org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.makeConn
ection(HttpURLConnectionImpl.java:267)
03-25 10:55:32.636: W/System.err(18868):at
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.connect
(HttpURLConnectionImpl.java:205)
03-25 10:55:32.636: W/System.err(18868):at 
org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnectionImpl.getOutputS
tream(HttpURLConnectionImpl.java:614)
03-25 10:55:32.636: W/System.err(18868):at 
com.myapp.core.JSONRequest.RequestWithHttpUrlConn(JSONRequest.java:63)
03-25 10:55:32.636: W/System.err(18868):    at com.myapp.core.DetailPage
$AsyncRecBooks.doInBackground(AKBookDetailView.java:265)
03-25 10:55:32.640: W/System.err(18868):    at com.myapp.core.DetailPage
$AsyncRecBooks.doInBackground(AKBookDetailView.java:1)
03-25 10:55:32.640: W/System.err(18868):    at android.os.AsyncTask$2.call
(AsyncTask.java:185)
03-25 10:55:32.640: W/System.err(18868):    at java.util.concurrent.FutureTask
$Sync.innerRun(FutureTask.java:306)
03-25 10:55:32.640: W/System.err(18868):    at java.util.concurrent.FutureTask.run
(FutureTask.java:138)
03-25 10:55:32.640: W/System.err(18868):    at 
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
03-25 10:55:32.648: W/System.err(18868):    at 
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
03-25 10:55:32.648: W/System.err(18868):    at java.lang.Thread.run(Thread.java:1019)
03-25 10:55:32.652: E/JSON Parser(18868): Error parsing data org.json.JSONException:  
End of input at character 0 of 

What's a solution for this?

Hatty answered 25/3, 2013 at 5:52 Comment(10)
I think this is your network problemFinn
I tested this on a hispeed wi-fi...still this occurs frequently...Hatty
set a connection timeout.Lachrymal
@akh : make sure u are using right webservice url for making httppost request or server is runningMotorboat
#4578304Lachrymal
@akh It is not about the speed of the connection, but it is because of the response from the server, try to call the same url from the browser window and check how much time will it take..Finn
@ρяσѕρєяK 565 left to reach 30k. congs bro..I appreciate your contribution in SO.Finn
@Lachrymal Setting a connection timeout won't cure a connection timeout problem.Koons
@EJP can you please suggest a better solution for setting the connection Timeout period in volleyBargello
In My case it comes when API is blocked i,e time duration for hosting is expired. From all the discussion above.I think it comes when Network Problem.There is not any issues in your code.Grindle
H
82

I've searched all over the web and after reading lot of docs regarding connection timeout exception, the thing I understood is that, preventing SocketTimeoutException is beyond our limit. One way to effectively handle it is to define a connection timeout and later handle it by using a try-catch block. Hope this will help anyone in future who are facing the same issue.

HttpUrlConnection conn = (HttpURLConnection) url.openConnection();

//set the timeout in milliseconds
conn.setConnectTimeout(7000);
Hatty answered 28/3, 2013 at 14:29 Comment(7)
Changing the timeout period doesn't constitute 'handling it'. Catching the exception does, but you were already doing that. None of this actually solves the problem, which is a network connectivity issue, not a programming issue at all.Koons
i agree that this is 100% network issue, not a programming issue...By 'handling' i mean to save the app from crash...All i want is to come out of the app when this happens......and regarding catching the exception, earlier I was not catching the SocketTimeoutException...So i catch that exception and come out of the app.Hatty
My connection time & readTimeOut is set to 20 * 1000, Still getting the SocketTimeOutException!Monaural
@MuhammadBabar It means the network has some issue that after 20 seconds no response had come. You need to catch the SocketTimeoutException and handle the situation appropriately.Hatty
@akh well i'm already catching the exception and internet connection is also fine but still the exception occurs frequently!Monaural
@EJP If increasing the timeout is not a solution to the problem since it is networking issue as you mentioned, then what is the action need to be taken to overcome the issue ?Steady
i'm using retrofit i set a okhttp client and set like OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .build(); still i'm getting same issue ?Rancho
T
34

I'm aware this question is a bit old. But since I stumbled on this while doing research, I thought a little addition might be helpful.

As stated the error cannot be solved by the client, since it is a network related issue. However, what you can do is retry connecting a few times. This may work as a workaround until the real issue is fixed.

for (int retries = 0; retries < 3; retries++) {
    try {
        final HttpClient client = createHttpClientWithDefaultSocketFactory(null, null);
        final HttpResponse response = client.execute(get);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 200) {
            throw new IllegalStateException("GET Request on '" + get.getURI().toString() + "' resulted in " + statusCode);
        } else {                
            return response.getEntity();
        }
    } catch (final java.net.SocketTimeoutException e) {
        // connection timed out...let's try again                
    }
}

Maybe this helps someone.

Telemachus answered 7/7, 2014 at 16:2 Comment(0)
A
5

If you are using Kotlin + Retrofit + Coroutines then just use try and catch for network operations like,

viewModelScope.launch(Dispatchers.IO) {
        try {
            val userListResponseModel = apiEndPointsInterface.usersList()
            returnusersList(userListResponseModel)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

Where, Exception is type of kotlin and not of java.lang

This will handle every exception like,

  1. HttpException
  2. SocketTimeoutException
  3. FATAL EXCEPTION: DefaultDispatcher etc

Here is my usersList() function

@GET(AppConstants.APIEndPoints.HOME_CONTENT)
suspend fun usersList(): UserListResponseModel

Note: Your RetrofitClient Classs must have this as client

OkHttpClient.Builder()
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
Angular answered 8/6, 2020 at 15:51 Comment(0)
S
2

If you are testing the server in localhost your Android device must be connected to the same local network. Then the Server URL used by your APP must include your computer IP Address and not the "localhost" mask.

Survance answered 24/7, 2015 at 12:29 Comment(0)
M
2

I faced the same problem when connecting to EC2, the issue was with Security Group, I solved by adding the allowed IPs at port 5432

Mule answered 8/2, 2021 at 11:55 Comment(0)
E
0

I was facing this problem and the solution was to restart my modem (router). I could get connection for my app to internet after that.

I think the library I am using is not managing connections properly because it happeend just few times.

Egocentric answered 17/9, 2018 at 20:39 Comment(0)
R
0

For me, I just restarted my application and it has gone. If you are using emulator, try restarting it. If your are using physical device then check for internet connection. Give it a try!

Retinue answered 25/5, 2021 at 7:8 Comment(0)
E
-1

Set This in OkHttpClient.Builder() Object

val httpClient = OkHttpClient.Builder()
        httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
            .writeTimeout(5, TimeUnit.MINUTES) // write timeout
            .readTimeout(5, TimeUnit.MINUTES) // read timeout
Extramarital answered 6/3, 2019 at 6:19 Comment(0)
I
-2

I got this same error as I mistakenly changed the order of the statements

OkHttpClient okHttpClient = new OkHttpClient().newBuilder() .connectTimeout(20, TimeUnit.SECONDS).readTimeout(20,TimeUnit.SECONDS).writeTimeout(20, TimeUnit.SECONDS) .build();

After changing the order of writeTimeout and readTimeout, the error resolved. The final code I used is given below:

OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .build();
Irresoluble answered 3/12, 2018 at 19:10 Comment(1)
Changing the order should not have made a difference, since all it's doing is setting internal fields and then building the object.Dennadennard

© 2022 - 2024 — McMap. All rights reserved.