java调用javascript

Java调用JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

/**
* @version V1.0
* @date 2017-09-21 20:58
*/
public class JsTest {

private static final Logger logger = LoggerFactory.getLogger(JsTest.class);

public static void main(String[] args) {


String url = "//flights.ctrip.com/domesticsearch/search/SearchFirstRouteFlights?DCity1=BJS&ACity1=KMG&SearchType=S&DDate1=2017-09-22&IsNearAirportRecommond=0&LogToken=1bd69145999c49d391102da28ded88fe&CK=1E1CDC6F399D26F328ACAB7254823FA5"
+ "&rk=" + Math.random() * 10 + "204001";
String r = "0.4229086476791374857311";

ScriptEngineManager manager = new ScriptEngineManager();
// nashorn javascript
ScriptEngine engine = manager.getEngineByName("javascript");

String jsFileName = "doc/html/xiecheng/ajaxRequest.js"; // 读取js文件
// 执行指定脚本
BufferedReader br = null;
Invocable invoke = null;
try {
br = new BufferedReader(new FileReader(jsFileName));
engine.eval(br);
invoke = (Invocable) engine;
} catch (FileNotFoundException e) {
logger.error("", e);
} catch (ScriptException e) {
logger.error("", e);
}

Object o = null;
try {
// 调用方法,并传入两个参数
o = invoke.invokeFunction("ajaxRequest", url, r);
} catch (ScriptException e) {
logger.error("", e);
} catch (NoSuchMethodException e) {
logger.error("", e);
}

logger.info("执行js后的结果:\r\n{}", o);

}

}