gpt4 book ai didi

java - HTTP URL 连接中出现错误

转载 作者:行者123 更新时间:2023-12-01 23:56:57 25 4
gpt4 key购买 nike

我正在为我的学校开发一个应用程序,我想显示来自网站的新闻,所以我必须在我的应用程序中获取源代码。这是我从网站获取 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;
}

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

有人可以帮助我吗?

谢谢

乔纳森

最佳答案

您需要捕获 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();
}
}
}

希望它能对您有所帮助,并祝您的项目顺利。

关于java - HTTP URL 连接中出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15442546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com