在我的 android 应用程序中,我必须从 URL 获取 XML 数据(http://api.offersdb.com/distribution/beta/offers.json?api_key=demo&radius=10&postal_code=30305
) ,为此我正在使用以下代码,
try {
URL url = new URL(urlStr);
URLConnection urlConn = url.openConnection();
if (!(urlConn instanceof HttpURLConnection)) {
throw new IOException("URL is not an Http URL");
}
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
resCode = httpConn.getResponseCode();
if (resCode == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
}catch (Exception e) {
e.printStackTrace();
}
但它返回以下异常
java.net.UnknownHostException: Host is unresolved: api.offersdb.com:80
当我用 URL 中的 ipaddress(XX.XX.XXX.XX) 更改主机名 (api.offersdb.com) 时,我可以获得响应。我不知道为什么会遇到这个问题,请有人帮助我。
提前致谢
拉日本
最佳答案
您是否尝试过在 list 文件中设置以下权限?
<uses-permission android:name="android.permission.INTERNET" />
/亚历克斯
关于android - 在 android 中使用 HostName 时获取 java.net.UnknownHostException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5740748/