0

我正在为我的学校申请一个应用程序,我想显示来自网站的新闻,所以我必须在我的应用程序中获取源代码。这是我从网站获取 Html- 源代码的代码:

public String getHTML(String urlToRead) {
    URL url;
    HttpURLConnection conn;
    BufferedReader rd;
    String line;
    String result = "";
    try {
        url = new URL(urlToRead);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        rd.close();
    } catch (Exception e) {
        result += e.toString();
    }
    return result;
}

如果我有互联网连接,它工作正常,但如果没有连接,应用程序崩溃。如何在应用程序中显示错误,如果没有连接到 Internet,而不会崩溃?(对不起我的英语,我是来自德国的学生......)

谁能帮我?

谢谢

乔纳森

4

1 回答 1

3

您需要捕获 UnknownHostException:

同样,我会将您的方法更改为仅从连接返回 InputStream 并处理与之相关的所有异常。然后才尝试读取或解析它或用它做任何其他事情。您可以获取 errorInputStream 并将对象状态更改为错误(如果有)。你可以用同样的方式解析它,只是做不同的逻辑。

我会有更多类似的东西:

public class TestHTTPConnection {

    boolean error = false;

    public InputStream getContent(URL urlToRead) throws IOException {
        InputStream result = null;
        error = false;
        HttpURLConnection conn = (HttpURLConnection) urlToRead.openConnection();
        try {
            conn.setRequestMethod("GET");
            result = conn.getInputStream();
        } catch (UnknownHostException e) {
            error = true;
            result = null;
            System.out.println("Check Internet Connection!!!");
        } catch (Exception ex) {
            ex.printStackTrace();
            error = true;
            result = conn.getErrorStream();
        }
        return result;
    }

    public boolean isError() {
        return error;
    }

    public static void main(String[] args) {
        TestHTTPConnection test = new TestHTTPConnection();
        InputStream inputStream = null;
        try {
            inputStream = test.getContent(new URL("https://news.google.com/"));
            if (inputStream != null) {
                BufferedReader rd = new BufferedReader(new InputStreamReader(
                        inputStream));
                StringBuilder data = new StringBuilder();
                String line;
                while ((line = rd.readLine()) != null) {
                    data.append(line);
                    data.append('\n');
                }
                System.out.println(data);
                rd.close();
            }
        } catch (MalformedURLException e) {
            System.out.println("Check URL!!!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我希望它会对您有所帮助,并祝您的项目好运。

于 2013-03-15T22:23:41.223 回答