Потеряно уже очень много времени на вопрос - получить правельную страницу от сервера. Описание припона. Есть ресурс который надо читать переодически. Сейчас они ввели новшества с выходными данными на странице и вывод основных данных выполняет javascript через AJAX запросы. Наткнулся на ресурс под названием Rhino. Но его библиотеки как-то не проглатывают типичные для javascript вещи. Я там взял готовый пример под названием BrowserDisplayer.java. URL адрес умышленно изменён. Так вот в зависимости от Rhino js библиотеки меняется выбрасываемое исключение. Сам исходный код ниже. | Код | org.mozilla.javascript.EcmaError: ReferenceError: "XMLHttpRequest" is not defined. (httpunit#23) at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3229) at org.mozilla.javascript.ScriptRuntime.constructError(ScriptRuntime.java:3219) at org.mozilla.javascript.ScriptRuntime.notFoundError(ScriptRuntime.java:3292) at org.mozilla.javascript.ScriptRuntime.nameOrFunction(ScriptRuntime.java:1636) at org.mozilla.javascript.ScriptRuntime.name(ScriptRuntime.java:1575) at org.mozilla.javascript.Interpreter.interpretLoop(Interpreter.java:3162) at script(httpunit:23) at script(httpunit:23) at org.mozilla.javascript.Interpreter.interpret(Interpreter.java:2251) at org.mozilla.javascript.InterpretedFunction.call(InterpretedFunction.java:161) at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:340) at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:2758) at org.mozilla.javascript.InterpretedFunction.exec(InterpretedFunction.java:172) at org.mozilla.javascript.Context.evaluateString(Context.java:1132) at com.meterware.httpunit.javascript.ScriptingEngineImpl.runScript(ScriptingEngineImpl.java:92) at com.meterware.httpunit.scripting.ScriptableDelegate.runScript(ScriptableDelegate.java:88) at com.meterware.httpunit.parsing.NekoDOMParser.runScript(NekoDOMParser.java:151) at com.meterware.httpunit.parsing.ScriptFilter.getTranslatedScript(ScriptFilter.java:150) at com.meterware.httpunit.parsing.ScriptFilter.endElement(ScriptFilter.java:131) at org.cyberneko.html.filters.DefaultFilter.endElement(DefaultFilter.java:249) at org.cyberneko.html.filters.NamespaceBinder.endElement(NamespaceBinder.java:367) at org.cyberneko.html.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1015) at org.cyberneko.html.HTMLTagBalancer.endElement(HTMLTagBalancer.java:888) at org.cyberneko.html.HTMLScanner$SpecialScanner.scan(HTMLScanner.java:2831) at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:809) at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:478) at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:431) at org.apache.xerces.parsers.XMLParser.parse(Unknown Source) at org.apache.xerces.parsers.DOMParser.parse(Unknown Source) at com.meterware.httpunit.parsing.NekoHTMLParser.parse(NekoHTMLParser.java:48) at com.meterware.httpunit.HTMLPage.parse(HTMLPage.java:271) at com.meterware.httpunit.WebResponse.getReceivedPage(WebResponse.java:1301) at com.meterware.httpunit.WebResponse.getFrames(WebResponse.java:1285) at com.meterware.httpunit.WebResponse.getFrameRequests(WebResponse.java:1024) at com.meterware.httpunit.FrameHolder.updateFrames(FrameHolder.java:179) at com.meterware.httpunit.WebWindow.updateFrameContents(WebWindow.java:315) at com.meterware.httpunit.WebClient.updateFrameContents(WebClient.java:526) at com.meterware.httpunit.WebWindow.updateWindow(WebWindow.java:201) at com.meterware.httpunit.WebWindow.getSubframeResponse(WebWindow.java:183) at com.meterware.httpunit.WebWindow.getResponse(WebWindow.java:158) at com.meterware.httpunit.WebClient.getResponse(WebClient.java:122) at BrowserDisplayer.main(BrowserDisplayer.java:128) Exception: Script 'var MooTools={'version':'1.2.3'
|
| Код | import com.meterware.httpunit.*;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URL;
/** * This example is from * http://m0smith.freeshell.org/blog-portletunit/2008/05/bare * -bones-browser-launch-for-java-use * * @author Matthew O. Smith * */ public class BrowserDisplayer { /** * Show the response in a browser. * * @param response * the response * @throws Exception * on error */ public static void showResponseInBrowser(WebResponse response) throws Exception { String text = response.getText(); File f = File.createTempFile("httpUnit", ".html"); f.deleteOnExit(); PrintWriter fod = new PrintWriter(new FileOutputStream(f)); fod.print("<head><base href=\"'http://localhost'/\"> </head>"); fod.print(text); fod.close(); URL url = f.toURL(); openURL(url); }
/** * Bare Bones Browser Launch Version 1.5 (December 10, 2005) By Dem * Pilafian. Supports: Mac OS X, GNU/Linux, Unix, Windows XP * * Example Usage: String url = "http://www.centerkey.com/"; * BareBonesBrowserLaunch.openURL(url); Public Domain Software -- Free to * Use as You Like * * @param url * the url to open * @throws ClassNotFoundException * getting class * @throws NoSuchMethodException * yes * @throws SecurityException * well * @throws InvocationTargetException * trying to invloke * @throws IllegalAccessException * trying to access * @throws IllegalArgumentException * bad arguement * @throws IOException * opening window * @throws InterruptedException * waiting */ public static void openURL(URL url) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, IOException, InterruptedException { String osName = System.getProperty("os.name");
if (osName.startsWith("Mac OS")) { Class fileMgr = Class.forName("com.apple.eio.FileManager"); Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[] { String.class }); openURL.invoke(null, new Object[] { url.toString() }); } else if (osName.startsWith("Windows")) { String cmdLine = "rundll32 url.dll,FileProtocolHandler " + url.toString(); Process exec = Runtime.getRuntime().exec(cmdLine); exec.waitFor(); } else { // assume Unix or Linux String[] browsers = { "firefox", "mozilla", "opera", "konqueror", "epiphany", "netscape" }; String browser = null; for (int count = 0; count < browsers.length && browser == null; count++) { if (Runtime.getRuntime() .exec(new String[] { "which", browsers[count] }) .waitFor() == 0) { browser = browsers[count]; } } if (browser == null) { throw new IllegalStateException("Could not find web browser"); } else { Runtime.getRuntime().exec( new String[] { browser, url.toString() }); } } }
/** * open a given url indirectly * * @param params */ public static void main(String[] params) { try { if (params.length < 1) { System.out.println("Usage: java BrowserDisplay [url]"); System.out.println(""); System.out .println("will demonstrate usage with the url 'https://google.com' now ..."); String[] defaultParams = { "https://google.com" }; params = defaultParams; } // direct call first String url = params[0]; openURL(new URL(url)); // and now indirectly // create the conversation object which will maintain state for us WebConversation wc = new WebConversation();
// Obtain the main page on the meterware web site WebRequest request = new GetMethodWebRequest(url); WebResponse response = wc.getResponse(request);
System.out.println("Response: " + response.getText());
// showResponseInBrowser(response);
// find the link which contains the string "HttpUnit" and click it // WebLink httpunitLink = response.getFirstMatchingLink( // WebLink.MATCH_CONTAINED_TEXT, "HttpUnit" ); // response = httpunitLink.click(); showResponseInBrowser(response); System.out.println("Your browser should show three pages now:"); System.out.println("1. a direct invocation of " + url); System.out.println("2. an indirect invocation of " + url + " via httpunit"); System.out .println("3. the result httpunit clicking the httpunit link on 2.");
} catch (Exception e) { System.err.println("Exception: " + e.getMessage()); } } }
|
После всего этого мне пришла идея подключиться к Firefox и через Firebug взять Response. Но опять же не нашёл примеров таких действий. Вообще возможно подключиться через некие библиотеки к браузеру??? Если есть у кого-то опыт выполнения javascript на стороне JAVA кода, я готов рассмотреть все версии. Это сообщение отредактировал(а) xrbyte - 12.8.2013, 17:09
|