我正在使用HttpURLConnection与我的应用程序中的服务器通信。但是我发现,如果我的android设备连接不良,我的应用程序将挂起很长时间,这是糟糕的用户体验。我同时使用setConnectTimeout()和setReadTimeout(),但似乎无法正常工作。这是我的代码如下:

        URL url = null;
        HttpURLConnection connection = null;
        InputStreamReader ins = null;
        try {
            url = new URL("XXXXXXXXXXXXXXXXX");
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(10000);
            connection.setReadTimeout(10000);
            ins = new InputStreamReader(connection.getInputStream());
            BufferedReader bufferedReader = new BufferedReader(ins);
            StringBuffer strBuffer = new StringBuffer();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                strBuffer.append(line);
            }
            result = strBuffer.toString();
            line = null;
            strBuffer = null;
            bufferedReader = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
                connection = null;
            }
            if (ins != null) {
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                ins = null;
            }
            url = null;
        }


从我的代码中可以看到,当我的互联网连接状况不佳时,我同时使用了setConnectTimeout()和setReadTimeout()。但是,它仍然挂出很长时间(超过30秒甚至更长),并且最终会显示以下日志:

    07-17 13:27:47.200: W/System.err(18005): java.net.UnknownHostException: Unable to resolve host "server.ibaobeimao.com": No address associated with hostname
    07-17 13:27:47.200: W/System.err(18005):    at java.net.InetAddress.lookupHostByName(InetAddress.java:424)
    07-17 13:27:47.200: W/System.err(18005):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    07-17 13:27:47.200: W/System.err(18005):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
    07-17 13:27:47.200: W/System.err(18005):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:70)
    07-17 13:27:47.203: W/System.err(18005):    at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
    07-17 13:27:47.207: W/System.err(18005):    at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
    07-17 13:27:47.207: W/System.err(18005):    at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
    07-17 13:27:47.207: W/System.err(18005):    at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
    07-17 13:27:47.207: W/System.err(18005):    at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:316)
    07-17 13:27:47.207: W/System.err(18005):    at libcore.net.http.HttpEngine.connect(HttpEngine.java:311)
    07-17 13:27:47.210: W/System.err(18005):    at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:290)
    07-17 13:27:47.210: W/System.err(18005):    at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:240)
    07-17 13:27:47.210: W/System.err(18005):    at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:282)
    07-17 13:27:47.213: W/System.err(18005):    at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
    07-17 13:27:47.213: W/System.err(18005):    at utils.Rpc.httpRequest(Rpc.java:49)
    07-17 13:27:47.213: W/System.err(18005):    at utils.Utils$11.run(Utils.java:1154)
    07-17 13:27:47.213: W/System.err(18005):    at java.lang.Thread.run(Thread.java:856)
    07-17 13:27:47.213: W/System.err(18005): Caused by: libcore.io.GaiException: getaddrinfo failed: EAI_NODATA (No address associated with hostname)
    07-17 13:27:47.217: W/System.err(18005):    at libcore.io.Posix.getaddrinfo(Native Method)
    07-17 13:27:47.217: W/System.err(18005):    at libcore.io.ForwardingOs.getaddrinfo(ForwardingOs.java:60)
    07-17 13:27:47.217: W/System.err(18005):    at java.net.InetAddress.lookupHostByName(InetAddress.java:405)
    07-17 13:27:47.217: W/System.err(18005):    ... 16 more
    07-17 13:27:47.217: W/System.err(18005): Caused by: libcore.io.ErrnoException: getaddrinfo failed: ETIMEDOUT (Connection timed out)
    07-17 13:27:47.220: W/System.err(18005):    ... 19 more


因此,我该如何设置HttpURLConnection超时时间?为什么setConnectTimeout()和setReadTimeout()不起作用?

这是我在android中使用ping的尝试,但是由于某些未知的原因,它仍然无法正常工作,但是我将列出我使用的方法:

public static final boolean ping() {

    String result = null;
    try {
        String ip = "202.108.22.5"; // ping address
        Process p = Runtime.getRuntime().exec("/system/bin/ping -c 1 -w 10 " + ip); // ping 3 times

        InputStream input = p.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
        StringBuffer stringBuffer = new StringBuffer();
        String content = "";
        while ((content = in.readLine()) != null) {
            stringBuffer.append(content);
        }

        // ping's situation
        int status = p.waitFor();
        if (status == 0) {
            result = "success";
            return true;
        } else {
            result = "failed";
        }
    } catch (IOException e) {
        result = "IOException";
    } catch (InterruptedException e) {
        result = "InterruptedException";
    } finally {
        Log.d("----result---", "result = " + result);
    }
    return false;
}


但是无论我是否真正连接到互联网,我的结果始终都是错误的。有人可以给我更多建议吗?

最佳答案

不幸的是,您的问题出在较低的网络层。您的参数仅在请求HTTP时起作用。您被困在解析DNS中。
事件顺序:


解决DNS
建立TCP连接
发送HTTP请求
接收HTTP响应


我唯一想到的是进行连接检查,例如打开与google gen_204的连接。

10-08 18:14