开发者

Call Javascript from Java

I'm downloading a search result from a website using java which works great for the first page.

URL url = new URL(
        "http://www.geocaching.com/seek/nearest.aspx?country_id=79&as=1&ex=0");
BufferedReader in = new BufferedReader(new InputStreamReader(
        url.openStream()));

String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}
in.close();

But how could I get the second page of the result? The link to the second page uses a javascript call javascript:__doPostBack('ctl00$ContentBody$pgrBottom$lbGoToPage_2',''), which calls this function:

<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['aspnetForm'];
if (!theForm) {
  theForm = document.aspnetForm;
}
function __doPostBack(eventTarget, eventArgument) {
  if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
      theForm.__EVENTTARGET.value = eventTarget;
      theForm.__EVENTARGUMENT.value = eventArgument;
      theForm.submit();
  }
}
//]]>
</script>

I think, i need to call 开发者_如何学Pythonthe function from my java programm to get the second page, but how?


From what I can tell you want to execute __doPostBack(...) as if it were on a web page executing in a browser. I can't see how you could do that programmatically using Java. If I were you I would try and manually create the post request that the Javascript is invoking (maybe using something like this). I know its not ideal because if the page changes your application wont work anymore but its the only reasonable solution I can think of.

Can I ask what exactly you are trying to achieve? Would something like Selenium help?


check out javax.script.ScriptEngine and javax.script.ScriptEngineManager and other stuff in the package:

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
engine.eval(...);


Try using Direct Web Remoting (DWR). This engine supports calling java methods from JavaScript and vice versa. Find more info at http://directwebremoting.org/dwr/index.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜