Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- import java.util.Scanner;
- import java.nio.charset.StandardCharsets;
- public class getURL {
- public static void main(String[] args) {
- String artistOrMbid = "";
- System.out.print("Enter artist name>");
- Scanner input = new Scanner(System.in);
- artistOrMbid = input.nextLine();
- input.close();
- // Pull the artist image url from the last.fm artist page
- String sImageURL = "", sArtistURL = "";
- try {
- sArtistURL = "https://www.last.fm/music/"+URLEncoder.encode(artistOrMbid, StandardCharsets.UTF_8.toString());
- } catch (UnsupportedEncodingException e) {
- // This should never happen for us
- }
- String sHTML = getWebPage(sArtistURL);
- if (sHTML != null) {
- int iImgUrlIndex = sHTML.indexOf("+images/");
- if (iImgUrlIndex > 0) {
- int iStartTrim = iImgUrlIndex+8; // ("+images/").length = 8
- int iEndTrim = sHTML.indexOf("\"", iStartTrim);
- String sImageID = sHTML.substring(iStartTrim, iEndTrim);
- sImageURL = "https://lastfm.freetls.fastly.net/i/u/770x0/"+
- sImageID+".jpg";
- }
- }
- System.out.println(sImageURL);
- }
- // Pull an html page and return HTML in string
- private static String getWebPage(String sURL) {
- HttpURLConnection connection;
- int iResponse;
- try {
- URL requestURL = new URL(sURL);
- connection = (HttpURLConnection)requestURL.openConnection();
- connection.setRequestMethod("GET");
- iResponse = connection.getResponseCode();
- } catch (Exception e) {
- if (e instanceof MalformedURLException) {
- System.out.println(e.getMessage());
- } else if (e instanceof UnknownHostException) {
- System.out.println("Unknown host: "+e.getMessage());
- } else if (e instanceof ConnectException) {
- System.out.println(e.getMessage());
- } else {
- System.out.println(e);
- }
- return null;
- }
- // Non-200 response means we did something wrong
- if (iResponse != 200) {
- System.out.println("Server returned error code: "+iResponse);
- return null;
- }
- // Constructed string from HTTP stream
- StringBuffer response = new StringBuffer();
- try {
- // Download the response from the server
- InputStream stream = connection.getInputStream();
- BufferedReader in = new BufferedReader(new InputStreamReader(stream));
- String readLine;
- while ((readLine = in.readLine()) != null)
- response.append(readLine);
- in.close();
- } catch (Exception e) {
- System.out.println("Error downloading responce from server!");
- }
- return response.toString();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement