-1

如果电话无法联系服务器,我将如何设置超时?这背后的原因是我有一个不断旋转的加载对话框,我希望连接在 10 秒后放弃,这将关闭加载对话框。

public class GetResults {
String data = null;
String URLME = null;
String Search = null;
BufferedReader inn;

@SuppressWarnings("finally")
public String GetLocationData(String THESEARCHSTRING) throws Exception {
    Search = THESEARCHSTRING;
    try {
        URL site = new URL("http://www.google.com/");
        java.net.URLConnection yc = site.openConnection();
        inn = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String ln = System.getProperty("line.separator");
        while ((l = inn.readLine()) != null) {
            sb.append(l + ln);
        }
        inn.close();

        data = sb.toString();
        URLME = data;
        return URLME;
    } finally {
        if (inn != null) {
            try {
                inn.close();
                return URLME;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return URLME;
    }
}

}

4

1 回答 1

0

请尝试使用它并检查是否增加超时时间。

导入 java.io.BufferedReader;导入 java.io.InputStreamReader;导入 java.net.URL;

公共类 c { 静态字符串数据 = null; 静态字符串 URLME = null; 静态字符串搜索 = null; static BufferedReader 客栈;

@SuppressWarnings("finally")
public static String GetLocationData(String THESEARCHSTRING)
        throws Exception {
    Search = THESEARCHSTRING;
    try {
        URL site = new URL("http://www.google.com/");
        java.net.URLConnection yc = site.openConnection();
        yc.setConnectTimeout(1);
        inn = new BufferedReader(new InputStreamReader(yc.getInputStream()));
        StringBuffer sb = new StringBuffer("");
        String l = "";
        String ln = System.getProperty("line.separator");
        while ((l = inn.readLine()) != null) {
            sb.append(l + ln);
        }
        inn.close();

        data = sb.toString();
        URLME = data;
        return URLME;
    } finally {
        if (inn != null) {
            try {
                inn.close();
                return URLME;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return URLME;
    }
}

}

于 2013-07-18T05:25:35.443 回答