我使用以下代码来发布 HTTP GET 并检索响应:
boolean download(String url)
{
try
{
java.net.URL connectURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
conn.connect();
conn.getOutputStream().flush();
try( InputStream is = conn.getInputStream() )
{
int ch;
StringBuilder sb = new StringBuilder();
while( ( ch = is.read() ) != -1 )
{
sb.append( (char)ch );
}
mScores = sb.toString();
}
catch( final Exception e)
{
mReceiver.exception("biffed it getting HTTPResponse");
return false;
}
}
catch( final Exception e )
{
mReceiver.exception(e.getMessage());
return false;
}
return true;
}
除了错误情况外,一切都运行良好。例如,如果我关闭运行此代码的设备上对互联网的访问并尝试
download("http://example.com/download.cgi");
那么我的用户看到的异常(上面的 mReceiver.exception(e.getMessage()) )是
Unable to resolve host 'example.com': No address associated with hostname
这对于开发者来说可能是可以理解的,但恕我直言,它不够用户友好。我想要类似“无法访问互联网,无法访问服务器‘example.com’”或者甚至更简单的“无法访问互联网”。
因此我的问题是:有没有办法从上面的代码返回有意义的、用户友好的错误字符串?
最佳答案
好吧,您可以捕获特定类型的异常(这需要在 catch(final Exception e)
之前进行):
catch( final java.net.UnknownHostException e )
{
mReceiver.exception("No access to Internet, failed to reach server '" + url + "'");
return false;
}
关于java - 来自 HttpURLConnection 的有意义的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60173577/