Search code examples
javajavascriptnashorn

Casting URLConnection to HttpUrlConnection in Nashorn


I've got some code:

var Base64 = java.util.Base64;
var URL = java.net.URL;
var HttpURLConnection = java.net.HttpURLConnection;
var connectionAddress = new URL("http://twitter.com/");
var httpConnection = Java.to(
        connectionAddress.openConnection(),
        Java.type("java.net.HttpURLConnection")
    );

this throws an exception: TypeError: sun.net.www.protocol.http.HttpURLConnection:http://twitter.com/ is not an Object

anyone have any ideas how to handle this?


Solution

  • Java.to is used to convert a JavaScript object to a Java object. Currently it supports conversion to Java array types, as well as java.util.List and java.util.Deque. It can't be used to "cast" between Java types, and anyway, it's not a meaningful concept in a dynamic language. Your openConnection() invocation gave you back a Java object of type sun.net.www.protocol.http.HttpURLConnection, which sounds like something that is already a subclass of java.net.HttpURLConnection, so you should all be set just by writing

    var httpConnection = connectionAddress.openConnection();