Request URL in Javascript, Fetch URL Content using Java Applet, return to Javascript?
- by Sam G
I'm in the process of making a little experiment, it grabs a YouTube page, and returns the highest quality MP4 link, then plays this in a HTML 5 Video element.
Now I was using PHP with cURL to get the URL content (YouTube), but that only works on my local server (MP4 link is locked to IP address). I can't think of any other way to get the page content due to cross domain rules except a Java applet.
So I've built a Java applet that should return the content of a URL.
Java
import java.applet.Applet;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLFetcherabc extends Applet
{
public void init()
{
}
public void paint(Graphics g) {
g.drawString("Java loaded. Waiting for URL", 0, 10);
}
public String getURL(String url, String httpMethod)
{
try
{
URL u = new URL(url);
HttpURLConnection conn = (HttpURLConnection)u.openConnection();
conn.setRequestMethod(httpMethod);
InputStream is = conn.getInputStream();
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for (int bytesRead = 0; (bytesRead = is.read(buffer)) != -1; ) {
output.write(buffer, 0, bytesRead);
}
return output.toString();
} catch (Exception e) {
}return null;
}
}
Now I've got the applet on the page, but every-time I call the function it returns nothing.
Heres my HTML for including the applet.
HTML
<applet id="URLFetcher" name="URLFetcher" code="URLFetcherabc.class" archive="URLFetcher.jar" height="200" width="200" mayscript=""></applet>
Java-Script
function fetchurl(urltofetch)
{
var URLFetcher = document.getElementById("URLFetcher");
var result = URLFetcher.getURL(urltofetch);
//Result = URL Content
return result;
}
The function always returns null, in Java the function does work when passed a variable via other means (parameter etc). I've tried running other functions through Javascript and the Java applet does respond. I'm new to Java applets and communicating with them via Javascript, so I'm probably making either a small mistake somewhere or its completely wrong.
Any ideas?
Thanks