RSSフィードを取得しようとしています。ただし、HttpEntity はこれを返します。
リソースが見つかりません
リソースが見つかりません
私が使用しているアドレスは、ブラウザで正常に動作します。
MainActivity.java:
...
String URL = "http://rss.nytimes.com/services/xml/rss/nyt/Africa.xml";
// XML node keys
String KEY_ITEM = "item"; // parent node
String KEY_TITLE = "title";
String KEY_PUBDATE = "pubDate";
String KEY_CREDIT = "media:credit";
XMLParser parser = new XMLParser();
String xml = parser.getXmlFromUrl(URL); // getting XML
mOutput += xml;
Document doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes <item>
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_TITLE, parser.getValue(e, KEY_TITLE));
map.put(KEY_PUBDATE, parser.getValue(e, KEY_PUBDATE));
map.put(KEY_CREDIT, parser.getValue(e, KEY_CREDIT));
}
...
XMLParser.java:
public class XMLParser {
public String getXmlFromUrl(String url) {
String xml = null;
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
xml = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d("dsgv", "UnsupportedEncodingException");
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.d("dsgv", "ClientProtocolException");
} catch (IOException e) {
e.printStackTrace();
Log.d("dsgv", "IOException");
}
// return XML
return xml;
}
public Document getDomElement(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (SAXException e) {
Log.e("Error: ", e.getMessage());
return null;
} catch (IOException e) {
Log.e("Error: ", e.getMessage());
return null;
}
// return DOM
return doc;
}
public String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return this.getElementValue(n.item(0));
}
public final String getElementValue( Node elem ) {
Node child;
if( elem != null){
if (elem.hasChildNodes()){
for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
if( child.getNodeType() == Node.TEXT_NODE ){
return child.getNodeValue();
}
}
}
}
return "";
}
}