用 Java 提交 HTML 表单
我正在尝试填写 HTML 表单,按下表单的提交按钮,然后从中获取响应。
填写表格效果非常好,但我不知道如何按页面上的提交按钮。
我正在使用 apache httpclient 库。
我的代码是:
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(pUrl);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("filter_response_time_http", "1"));
nvps.add(new BasicNameValuePair("filter_port", "80"));
nvps.add(new BasicNameValuePair("filter_country", "US"));
nvps.add(new BasicNameValuePair("submit", "Anzeigen"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
提交按钮的代码是:
<input onclick="doSubmit();" id="submit" type="submit" value="Anzeigen" name="submit" />
I am trying to fill in a HTML Form, press a submit button of the form and then get the response from it.
Filling in the form works really well but i can't figure out how to press the submit button on the page.
I am using the apache httpclient libraries.
My code is:
httpclient = new DefaultHttpClient();
HttpPost httpost = new HttpPost(pUrl);
List <NameValuePair> nvps = new ArrayList <NameValuePair>();
nvps.add(new BasicNameValuePair("filter_response_time_http", "1"));
nvps.add(new BasicNameValuePair("filter_port", "80"));
nvps.add(new BasicNameValuePair("filter_country", "US"));
nvps.add(new BasicNameValuePair("submit", "Anzeigen"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
response = httpclient.execute(httpost);
entity = response.getEntity();
The code for the submit button is:
<input onclick="doSubmit();" id="submit" type="submit" value="Anzeigen" name="submit" />
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不需要使用 HttpClient“单击按钮”;它所做的只是 HTTP 的东西,与 JS 和 DOM 无关。
如果您想模拟浏览器,请使用类似 JWebUnit 的东西,它可以驱动 HttpClient 和 Selenium,并提供 JavaScript支持。
You don't "click a button" with HttpClient; all it does is HTTP stuff, which is unrelated to JS and the DOM.
If you want to emulate a browser, use something like JWebUnit, which can drive both HttpClient and Selenium, and provides JavaScript support.
单击提交按钮时会调用 JavaScript 函数。您无法使用 Java 代码模拟该行为。
为此,您需要使用像 htmlunit 这样可以处理 javascript 的无头浏览器。
Your submit button calls a javascript function when clicked. You can't emulate that behaviour using your java code.
For that you need to use a headless browser like htmlunit which can handle javascript.