Getting java.net.SocketTimeoutException: connection timeout in android

I am relatively new to Android development. I am developing an Android application where I submit a request to a web server and parse json objects. Often I get a java.net.SocketTimeoutException: Connection timed out exception when communicating with the server. Several times it will work without problems. I know that the same question has been asked in SO many times. But still I did not get a satisfactory solution to this problem. I am 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 

Can someone help me find a solution for this? Thanks in Advance ....

+61
java android java-io
Mar 25 '13 at 5:52
source share
7 answers

I searched all over the Internet and, after reading a lot of documents about connection timeout exceptions, I realized that preventing a SocketTimeoutException is beyond our limit ... One way to effectively manage is to determine the connection timeout and process it later using a block catch try ... hope this helps anyone in the future who is facing the same problem.

 HttpUrlConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(7000); //set the timeout in milliseconds 
+49
Mar 28 '13 at 14:29
source share
— -

I know this question is a bit outdated. But since I stumbled upon this during research, I thought that a small supplement could be useful.

As indicated, the error cannot be resolved by the client because it is a network-related problem. However, what you can do is try again several times. This may work as a temporary solution until the real problem 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 try again } } 

Maybe this helps someone.

+21
Jul 07 '14 at 16:02
source share

If you are testing the server on a local host, your Android device must be connected to the same local network. Then, the server URL used by your APP should contain the IP address of your computer, not the localhost mask.

+2
Jul 24 '15 at 12:29
source share

I ran into this problem and the solution was to restart my modem (router). After that, I can connect to my application on the Internet.

I think that the library I use does not manage connections properly, because it is happeend just a few times.

0
Sep 17 '18 at 20:39
source share

I got the same error as I mistakenly changed the order of 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 is resolved. The last code I used is below:

 OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .build(); 
0
Dec 03 '18 at 19:10
source share
 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. 
0
Jan 18 '19 at 7:05
source share
 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(); } } } 
-four
Oct 11 '13 at
source share



All Articles