SocketTimeoutException in HttpURLConnection randomly in getResponseCode

倖福魔咒の 提交于 2021-02-07 08:47:11

问题


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.


回答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




回答2:


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



来源:https://stackoverflow.com/questions/34704045/sockettimeoutexception-in-httpurlconnection-randomly-in-getresponsecode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!