java调用javascript

Java调用JavaScript


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);

	}

}