android java http超时不起作用

时间:2013-07-18 00:31:43

标签: java android http

如果手机无法联系服务器,我如何设置超时? 这背后的原因是我有一个持续旋转的加载对话框,我希望连接在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;
    }
}

}

1 个答案:

答案 0 :(得分:0)

请尝试使用此功能并检查增加超时时间。

import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL;

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

@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;
    }
}

}