Search code examples
javavalidationinputhttp-live-streamingurlconnection

How to read a simple playlist in java


I am trying to create a simple java command line code that will accept the URL from a playlist in command line and it should return the playlist content.

I am getting the following response back Enter playlist url here (0 to quit): http://gv8748.lu.edu:8084/sweng987/simple-01/playlist.m3u8 java.net.MalformedURLException: no protocol: http://lu8748.lu.edu:8084/sweng987/simple-01/playlist.m3u8

at java.base/java.net.URL.<init>(URL.java:627)
at java.base/java.net.URL.<init>(URL.java:523)
at java.base/java.net.URL.<init>(URL.java:470)
at edu.lu.sweng987.SimplePlaylist.getPlaylistUrl(SimplePlaylist.java:36)
at edu.lu.sweng987.SimplePlaylist.main(SimplePlaylist.java:21)

My code is the following

package edu.psgv.sweng861;
import java.util.Scanner; 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.*;

public class SimplePlaylist {

	private SimplePlaylist() {
		//don't allow instances
	}
	// The main function returns the URL entered 
	public static void main(String[] args) throws IOException{ 
		String output = getPlaylistUrl("");
		System.out.println(output);
		
		
	}
	

	private static String getPlaylistUrl(String theUrl) {
		String content = "";
		Scanner scanner = new Scanner(System.in);
		boolean validInput = false; 

		System.out.println("Enter playlist url here (0 to quit):");
		 content = scanner.nextLine();
		try {
			URL url = new URL(theUrl);
			URLConnection urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
			String line;
			
			while ((line = bufferedReader.readLine()) != null) {
				content += line + "\n";
			}
			bufferedReader.close();
		} catch(Exception e) {
			
			e.printStackTrace();
		}  
		return content;
	}

	
	
}


Solution

  • You have incorrectly used the parameter for the method when creating the URL instance instead of the local variable actually containing the url

    Change

    content = scanner.nextLine();
    try {
       URL url = new URL(theUrl);
    

    to

    content = scanner.nextLine();
    try {
       URL url = new URL(content);