我正在尝试从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文档非常全面,查看每个人最喜欢的艺术家Benny Hill的样本响应将为您找到合适的图像显示提供足够的指导。
编辑:对于API的一个例子,你可以看看官方的Last.fm客户端-但要注意,这是GPL3授权的东西,除非你想发布你的源代码,否则你不应该玩太多的副本&粘贴
编辑(再次):对于一个没有被GPL3污染的示例,请尝试以下操作:
(该示例使用友好的XML解析器JSoup)
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;
}
}