我的doGet中有一个方法,如果日期不等于今天,它就会启动一个线程。调度程序将找到 execute(( 方法。在此方法((中,我尝试使用重定向。
方法一:我使用脚本引擎通过Java调用我的js方法,但它总是给我以下错误:
Js 方法:
function httpGet(theUrl){
window.open(theUrl)
}
爪哇方法:
ScriptEngine engine = manager.getEngineByName("js");
// read script file
engine.eval(Files.newBufferedReader(Paths.get(url), StandardCharsets.UTF_8));
Invocable inv = (Invocable) engine;
// call function from script file
inv.invokeFunction("httpGet", "http://localhost:8080/myProject/StartScript?duration="+minutes);
错误:
javax.script.ScriptException: ReferenceError: "window" is not defined in <eval> at line number 3
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeImpl(NashornScriptEngine.java:392)
at jdk.nashorn.api.scripting.NashornScriptEngine.invokeFunction(NashornScriptEngine.java:190)
at watering.WateringScheduler.execute(WateringScheduler.java:99)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:557)Caused by: <eval>:3 ReferenceError: "window" is not defined
方法2:
我尝试使用HttpUrlConnection,但问题是即使它连接,它也永远不会将我重定向到该页面。
URL url;
log.info("hi "+ minutes);
url = new URL("http://localhost:8080/myProject/StartScript?duration="+minutes);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
int responseCode = urlConnection.getResponseCode();
System.out.println(responseCode);
if(responseCode==200) {
urlConnection = (HttpURLConnection) url.openConnection();
System.out.println("Redirect to URL : " + url);
}
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
StringBuffer html = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
html.append(inputLine);
}
in.close();
问题是我在网上阅读的所有内容都指向通过doGet或doPost重定向。我想通过我的 execute(( 方法重定向。
谢谢!
Java 中的脚本引擎提供了执行 Javascript 代码的能力,但不提供浏览器的模拟。使用 http 客户端(如 okhttp(下载页面的原始 HTML。
欲了解更多信息,请访问"document"未在java ScriptEngine中定义