如何从Feed链接对象数组中获取图片、PDF类型的目标URL
Solution: Dynamically Extract Image and PDF URLs from OPDS Feed
Instead of relying on fixed array indices (which breaks if the feed structure changes), we can iterate through all links in each entry and filter them based on their MIME type (or relation attribute, if needed). Here's how to rewrite your code:
Modified Code
URL url = new URL("https://catalog.example.com/publicdomain/browse/en/recent.atom"); XmlReader xmlReader = null; try { xmlReader = new XmlReader(url); SyndFeed feeder = new SyndFeedInput().build(xmlReader); // Use generic iterator for type safety for (Iterator<SyndEntry> entryIterator = feeder.getEntries().iterator(); entryIterator.hasNext();) { SyndEntry syndEntry = entryIterator.next(); System.out.println("Author: " + syndEntry.getAuthor()); // Iterate through all links in the entry for (SyndLink link : syndEntry.getLinks()) { String linkType = link.getType(); // Filter links by MIME type: images and PDFs if (linkType != null && (linkType.startsWith("image/") || linkType.equals("application/pdf"))) { System.out.println("\nRelevant Link Found:"); System.out.println(" MIME Type: " + linkType); System.out.println(" URL: " + link.getHref()); // Optional: Check relation for thumbnail-specific images String linkRel = link.getRel(); if (linkRel != null) { System.out.println(" Relation: " + linkRel); } } } System.out.println("------------------------"); } } finally { if (xmlReader != null) xmlReader.close(); }
Key Changes Explained
- No fixed indices: We loop directly through
syndEntry.getLinks()instead of converting to an array and hardcoding positions. This makes the code resilient to feed structure changes. - MIME type filtering: We check if the link's
typestarts withimage/(covers all image formats like JPEG, PNG) or exactly matchesapplication/pdf(for PDFs). This is the most reliable way to identify content types. - Optional relation check: If you specifically need thumbnails (like your original
str[3]example), you can add an extra condition for therelattribute (e.g.,linkRel.equals("http://opds-example.org/image/thumbnail")). - Type safety: Using
Iterator<SyndEntry>avoids unnecessary casting and makes the code cleaner.
Example Output
For your original thumbnail link, the output would look like:
Author: John Doe Relevant Link Found: MIME Type: image/jpeg URL: https://covers.example.net/book/6709.jpg Relation: http://opds-example.org/image/thumbnail ------------------------
内容的提问来源于stack exchange,提问作者user2341596
相关产品推荐
相关产品推荐

