java – Last.fm不会返回艺术家图片
作者:互联网
我正在尝试从Last.fm获取并应用艺术家图像到ImageView,但没有返回任何图像.我不确定我在这里做错了什么.
private void setLastFmArtistImage() {
try {
String imageurl = "http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="
+ URLEncoder.encode("Andrew Bird")
+ "&api_key="
+ APIKEY
+ "&limit=" + 1 + "&page=" + 1;
InputStream in = null;
Log.i("URL", imageurl);
URL url = new URL(imageurl);
URLConnection urlConn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) urlConn;
httpConn.connect();
in = httpConn.getInputStream();
Bitmap bmpimg = BitmapFactory.decodeStream(in);
mArtistBackground.setImageBitmap(bmpimg);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
解决方法:
您尝试使用的API会返回XML,而不是图像.您需要解析响应并从响应中选择适当的图像URL.
API documentation是非常彻底的,查看每个喜欢的艺术家Benny Hill的样本响应将为您提供足够的方向来找到合适的图像来显示.
编辑:有关API的示例,您可以查看官方Last.fm client – 请注意,这是GPL3授权的东西,除非您想要发布您的来源,否则您不应该使用副本&糊.
编辑(再次):对于未受GPL3污染的示例,请尝试以下操作:
(该示例使用JSoup,友好的XML解析器)
public List<LastFmImage> getLastFmImages(String artistName, int limit, int page) throws IOException {
String apiUrl = "http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="
+ URLEncoder.encode(artistName)
+ "&api_key="
+ APIKEY
+ "&limit=" + limit + "&page=" + page;
Document doc = Jsoup.connect(apiUrl).timeout(20000).get();
Elements images = doc.select("images");
ArrayList<LastFmImage> result = new ArrayList<LastFmImage>();
final int nbrOfImages = images.size();
for (int i = 0; i < nbrOfImages; i++) {
Element image = images.get(i);
String title = image.select("title").first().text();
Elements sizes = image.select("sizes").select("size");
final int nbrOfSizes = sizes.size();
for (int j = 0; j < nbrOfSizes; j++) {
Element size = sizes.get(i);
result.add(new LastFmImage(title, size.text(),
size.attr("name"),
Integer.parseInt(size.attr("width")),
Integer.parseInt(size.attr("height"))));
}
}
return result;
}
和LastFmImage类:
public class LastFmImage {
public String mTitle;
public String mUrl;
public String mName;
public int mWidth;
public int mHeight;
public LastFmImage(String title, String url, String name, int width, int height) {
mTitle = title;
mUrl = url;
mName = name;
mWidth = width;
mHeight = height;
}
}
标签:android,java,bitmap,last-fm 来源: https://codeday.me/bug/20190826/1731273.html