3

I am getting following error in con.getResponseCode()

java.net.SocketTimeoutException: failed to connect to example.com (port 80) after 3000ms
at libcore.io.IoBridge.connectErrno(IoBridge.java:223)
at libcore.io.IoBridge.connect(IoBridge.java:127)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:475)
at java.net.Socket.connect(Socket.java:861)
at com.android.okhttp.internal.Platform.connectSocket(Platform.java:152)
at com.android.okhttp.Connection.connect(Connection.java:101)
at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:294)
at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:296)
at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:503)

First time when it gets called it works perfectly. But it stops working after it and it may start working randomly after some time.

public class HTTPLoader {
    public static String loadContentFromURLGET(String urlString,List<String[]> getVars,Context context){
        int retry = 0;
        HttpURLConnection con=null;
        BufferedReader in = null;
        StringBuffer response=null;
        if (!isConnectingToInternet(context)){
            return "{'error':'No Internet connection!'}";
        }
        while (retry++<=RETRY_CNT) {
            try {
                String urlParameters = "";
                for (String[] var : getVars) {
                    urlParameters += var[0] + "=" + URLEncoder.encode(var[1], "UTF-8") + "&";
                }
                if (urlParameters.length() > 1) {
                    urlParameters = urlParameters.substring(0, urlParameters.length() - 1);
                }
                if (urlString.charAt(urlString.length() - 1) != '?') {
                    urlString += "&";
                }
                URL url = new URL(urlString + urlParameters);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(3000);
                con.setRequestMethod("GET");
                con.setRequestProperty("User-Agent", USER_AGENT);
                con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                con.setDoInput(true);
                con.setDoOutput(true);
                int responseCode = con.getResponseCode();
                in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                retry = RETRY_CNT+1;
                break;
            } catch (IOException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }finally {
                if (in!=null){
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (con!=null) {
                    con.disconnect();
                }
                in = null;
                con = null;
            }
        }
        if (response!=null)
            return new String(response);
        return "{'error':'No Internet connection!'}";
    }
}

This loadContentFromURLGET is getting called from IntentService

public class ChatUtil extends IntentService{
    protected String loadAllChats(String date){
            String response = "";
            try {
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                String email = sharedPreferences.getString(QuickstartPreferences.EMAIL, "");

            List<String[]> postVars = new ArrayList<>();
            postVars.add(new String[]{"getconversation", "yes"});
            postVars.add(new String[]{"user_id", email});
            postVars.add(new String[]{"last_date", date});
            String urlString = getString(R.string.get_conversation_url);
            response = HTTPLoader.loadContentFromURLGET(urlString, postVars,getApplicationContext());
            Log.i(TAG, response.toString());
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.has("error")) {
                //Toast.makeText(getApplicationContext(), jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
                return jsonObject.getString("error");
            }
        }catch (JSONException e) {
        }
    }
protected void onHandleIntent(Intent intent) {
    String task = intent.getStringExtra(QuickstartPreferences.CURRENT_TASK);
    Intent nintent;
    String date = "";
String[] arr3 = new NewsDBUtil(getApplicationContext()).getLastChatEntry(null);
            if (arr3!=null)
                date = arr3[1];
            loadAllChats(date);
            nintent = new Intent(QuickstartPreferences.LOADING_ALL_CHAT);
            LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(nintent);
           }
}

Tried closing and disconnecting stream in finally block. But no Success.

5
  • Three seconds is too short for a connect timeout. Increase it. Commented Jan 10, 2016 at 10:58
  • I have checked with 20000 also , but it behaves similarly. Commented Jan 10, 2016 at 11:05
  • did figure this out? Commented Sep 8, 2017 at 21:58
  • Can you try to remove your con.disconnect(); and see what happens? Since the connecion can be transparently shared among other instances this might cause the problem... Commented Apr 9, 2020 at 16:10
  • @Vijay Do you have any solution for that? I am facing this issue now. Commented Jul 20, 2022 at 7:38

2 Answers 2

1

you can put con.getResponseCode(); between try ...catch block if it throw SocketTimeoutException Exception make another try , but make sure you extend your timeout

if (responseCode != 200) {

           ....
           ...

    } catch (final java.net.SocketTimeoutException e) {
        // connection timed out...let's try again                
    } 

may this help

Sign up to request clarification or add additional context in comments.

1 Comment

My Question here is why it is giving SocketTimeOutException , even when i am connected to high-speed internet, also there is no problem on server side?
1

Without specific ContentLength via setFixedLengthStreamingMode

I found some devices generated incomplete http request

cause the server has to wait until either server or client timed out

you can use wireshark to analyze the problem

3 Comments

The same code posted above works fine , but it randomly stops working and gives socketTimeout . Also it starts working again after some time.
Yes that randomly exception happened to me too, did you try my approach? there are also other weird problem with HttpUrlConnection class, silently double post, EOFException randomly
Thanks this helped to bring down our timeouts quite a bit. For the remaining handful cases we do a retry and after one it always works. Strange thing why this happens in the first place though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.