我想解析受密码保护的RSS Feed中的数据。如果我尝试解析数据,它会抛出"文件未找到异常"
这是我的代码:
try {
DBF = DocumentBuilderFactory.newInstance();
DB = DBF.newDocumentBuilder();
url_val = new URL("http://admin:admin@dev.quaddeals.com/university-of-illinois/androids/city.rss");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
dom = DB.parse(url_val.openConnection().getInputStream());
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
elt = dom.getDocumentElement();
NodeList items = elt.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Node item = items.item(i);
NodeList properties = item.getChildNodes();
for (int j = 0; j < properties.getLength(); j++) {
Node property = properties.item(j);
String name = property.getNodeName();
if (name.equalsIgnoreCase("title")) {
cityTitle = property.getFirstChild().getNodeValue();
}
if (name.equalsIgnoreCase("id")) {
cityId = property.getFirstChild().getNodeValue();
}
}
title.add(cityTitle);
id.add(cityId);
}
VALUE1 = new String[title.size()];
Iterator<String> itc = title.iterator();
while (itc.hasNext()) {
l1++;
VALUE1[l1] = itc.next().toString();
}
VALUE2 = new String[id.size()];
Iterator<String> it1c = id.iterator();
while (it1c.hasNext()) {
m1++;
VALUE2[m1] = it1c.next().toString();
}
} catch (Exception e) {
}
我的Log Cat显示错误如下:
02-21 23:20:48.893: WARN/System.err(19206): java.io.FileNotFoundException: http://dev.quaddeals.com/university-of-illinois/androids/city.rss
02-21 23:20:48.893: WARN/System.err(19206): at org.apache.harmony.luni.internal.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1064)
02-21 23:20:48.893: WARN/System.err(19206): at com.fsp.quaddeals.DealCities$SelectDataTask_Deals.doInBackground(DealCities.java:341)
02-21 23:20:48.893: WARN/System.err(19206): at com.fsp.quaddeals.DealCities$SelectDataTask_Deals.doInBackground(DealCities.java:1)
如果我在浏览器中输入this URL,它将要求进行身份验证,之后它将重定向到我的解析数据所在的原始RSS FEED。
我想解析此页面中的数据。如何访问此受密码保护的页面并解析数据? Android是否支持SSL连接。
答案 0 :(得分:1)
这里有几个选项。您可以手动设置它,如下所示:
URL url = new URL("http://admin:admin@dev.quaddeals.com/university-of-illinois/androids/city.rss");
URLConnection urlConnection = url.openConnection();
if (url.getUserInfo() != null) {
String basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
urlConnection.setRequestProperty("Authorization", basicAuth);
}
dom = DB.parse(urlConnection.getInputStream());
您可以使用java.net.Authenticator
,但它可以全局(在所有网址上):
// see https://developer.android.com/reference/java/net/Authenticator.html
// and https://developer.android.com/reference/java/net/PasswordAuthentication.html
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});