Recuperar XML de URL
Frecuentes
Visto 362 veces
1
Tengo algunos problemas para recuperar un xml de la URL con el siguiente código:
private static String getAlbumArt(String artistName, String albumName){
try{
XMLParser xml_parser = new XMLParser();
String xml = xml_parser.getXmlFromUrl(getAlbumURL(artistName, albumName));
Document doc = xml_parser.getDomElement(xml);
NodeList N = doc.getElementsByTagName("album");
Node node = N.item(0);
NodeList N2 = node.getChildNodes();
System.out.println("1------");
for (int i = 0; i < N2.getLength(); i++) {
Node detailNode = N2.item(i);
if (detailNode.getNodeType() == Node.ELEMENT_NODE)
{
System.out.println("2------");
if (detailNode.getNodeName().equalsIgnoreCase("image"))
{
String sizeVal = ((Element) detailNode).getAttribute("size");
String url = detailNode.getTextContent();
if (sizeVal.equalsIgnoreCase("large")) {
return url;
}
}
}
}
}
catch (Exception e){
}
return null;
}
La función xml a la que llamo en el código anterior:
public String getXmlFromUrl(String url) {
String xml = null;
try {
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();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
getAlbumURL:
public static String getAlbumURL(String artist, String album){
return URL_METHOD + METHOD_GETALBUM + AMPERSAND
+ API_KEY + AMPERSAND
+ PARAM_ARTIST + artist + AMPERSAND
+ PARAM_ALBUM + album;
}
Analizador XML:
XMLParser de clase pública {
// constructor
public XMLParser() {
}
//Get XML from URL
public String getXmlFromUrl(String url) {
String xml = null;
try {
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();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return xml;
}
//Get dom element
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 doc;
}
//Get nod element
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 "";
}
//Get element value
public String getValue(Element item, String str) {
NodeList nlList = item.getElementsByTagName(str).item(0).getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
Algunas ideas ? En serio, no sé qué está mal. Utilicé esto antes y funcionó.
2 Respuestas
0
Saqué tu código y lo probé. Rehice "getAlbumURL" para devolver una cadena codificada. Usé la dirección que proporcionaste en los comentarios, falló. Sin embargo, ese xml no se vincula a ninguna carátula del álbum. Así que probé con el nombre correcto del álbum, "In%20ra*i*nbows". Funcionó como un sueño.
Entonces, primero, verifique que sus constantes le den lo que cree que deberían (lo cual ya hizo) y segundo, verifique sus datos de prueba. Su código parece estar bien.
Respondido el 28 de Septiembre de 12 a las 22:09
No estaba probando con la URL de ejemplo que le di, estaba usando solo artistas y álbumes de una palabra, y estaba generando valores correctos. No cambié nada y está funcionando ahora. Solo agregué un método para agregar% 20 a varios artistas y álbumes de palabras. No tengo idea de lo que me estaba perdiendo. gracias por tu tiempo! Realmente lo aprecio ! ;) - jason costa
0
faet DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
añadir estas líneas antes de la try{}
bloque:
dbf.setIgnoringComments(true);
dbf.setCoalescing(true);
Respondido 16 Feb 13, 16:02
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas android xml url or haz tu propia pregunta.
Por favor, publique cómo se ve su xml: antoniom
Me gusta: ws.audioscrobbler.com/2.0/… - Jason Costa
algún error? ¿Puede depurar y verificar que la cadena XML es XML válido es XML válido? - Billdr
Sin errores, la URL es correcta, cuando llega aquí: String xml = xml_parser.getXmlFromUrl(getAlbumURL(artistName, albumName)); la aplicación se detiene.. - Jason Costa
Intenté generar el XML y no aparece nada, pero estoy usando esa función en otra clase y funciona. Entonces, el problema solo puede estar en la primera parte del código. - Jason Costa