如何使用 android 中的 Jsoup 从新闻帖子中提取图像并加载到图像视图中?

How do I extract an image from a newspost using Jsoup in android an to load into imageview?

这是我的代码,它给我一个错误,指出 URL 无效,但我确信它是有效的,因为我可以通过浏览器获取图像。这是 link to the page.

// Connect to the web site
Document document = Jsoup.connect(newsImg).get();
// Using Elements to get the class data
Elements img = document.select("img[src]");
// Locate the src attribute
String imgSrc = img.attr("src");
// Download image from URL
InputStream input = new java.net.URL(imgSrc).openStream();
// Decode Bitmap
bitmap = BitmapFactory.decodeStream(input);

你没有指定你想要哪张图片,所以我假设你想要第一条新闻的图片。如果您在检查器中打开该页面(例如 Chrome 的开发工具),您可以看到图像有一个相对的 link,就像这个:/rf/image_size_800x600/HT/p2/2016/01/05/Pictures/india-airbase-attack_a23bb650-b38f-11e5-87b3-9157ef61c9c7.jpg,这很可能是你错误背后的动机。

如果您想下载图像,您必须提供完整的 URL,这是相对 URL 后跟的基本目标。在这种情况下,它解析为:http://www.hindustantimes.com/rf/image_size_800x600/HT/p2/2016/01/05/Pictures/india-airbase-attack_a23bb650-b38f-11e5-87b3-9157ef61c9c7.jpg

试试下面的代码。具体见里面的评论。

Document document = Jsoup.connect(newsLink).get();

// Instead of using Elements, we'll use Element class directly...
Element img = document.select("img#1").first();
if (img == null) { // Always check that the image has been foud
    throw new RuntimeException("Unable to locate image in " + newsLink);
}

// Locate the src attribute. You need an absolute URL here...
String imgSrc = img.absUrl("src"); // ... so we use `absUrl`

// Download image from URL
InputStream input = new java.net.URL(imgSrc).openStream();

//...