Applet URLConnection.connect fails after being cal

2019-02-25 18:37发布

问题:

I have a website with a Java Applet and that applet needs to connect to my server. This works in JApplets @Override init() but not in my own functions that are being called by javascript.

final URL url = new URL(SERVER_URL + action);
System.out.println("url:" + url);
System.out.println("postString: " + postString);
final HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if(!postString.isEmpty()) {
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    connection.setRequestProperty("Content-Length", Integer.toString(postString.getBytes().length));
    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    System.out.println("connecting...");
    connection.connect(); // same with connection.getOutputStream();
    System.out.println("connected");
    ....

website:

<a href="javascript: document.applet.update();" title="update from server">Update</a>
<applet id="applet" archive="/public/Antucation-0.1.0.jar?random=3765332307555812156" code="de.antucation.controller.Controller.class" width="100%" height="800px">
<param name="colonyId" value="1">
</applet>

output:

url:http://localhost:9000/applet/showCode
postString: colonyId=1
connecting...

I have a try catch around it with a System.out call but nothing happens there either. However this works absolutly fine:

@Override
public void init() {
    update();
}

Oh and the applet of course also comes from http://localhost:9000/

How do I work around this or fix it?

回答1:

Try something along the lines of:

public void callFromJavaScript(final String param) {
    AccessController.doPrivileged( new PrivilegedAction<Void>() {
        public Void run() {
            // call code to make the connection..
            return null;
        }
    });
}