使用Java以编程方式提交webest 's或blog's html表单
submit webiste's or blog's html form programmatically using Java
我正在尝试使用Java HttpClient提交一个网站的表单。
下面是html表单的代码:
<form action="http://bmlaps.org/wp-comments-post.php" method="post" id="commentform" class="comment-form" novalidate>
<input id="author" name="author" type="text" value="" size="30" aria-required='true' required='required' />
<input id="email" name="email" type="email" value="" size="30" aria-describedby="email-notes" aria-required='true' required='required' />
<textarea id="comment" name="comment" cols="45" rows="8" aria-describedby="form-allowed-tags" aria-required="true" required="required"></textarea>
<input name="submit" type="submit" id="submit" class="submit" value="Post Comment" />
</form>
下面是我的Java代码:
public static void postForm() {
String url = "someurl";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("author", "testAuthor"));
params.add(new BasicNameValuePair("email", "testmail@gmail.com"));
params.add(new BasicNameValuePair("comment", "test commment"));
try {
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity respEntity = response.getEntity();
if (respEntity != null) {
String content = EntityUtils.toString(respEntity);
System.out.println(content);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
谁能告诉我如何提交这个表格?
这是一个简单的认错案例。代码中的假设是HttpClient
将在网页中提交表单;因此,url
变量包含了保存html表单的网页的url(变量被掩盖了,但这在评论中讨论过)。
但这不是它的工作方式,您使用HttpClient来模拟浏览器在提交所述表单时所做的事情-即创建HTTP post请求并将参数作为数据的一部分传输到特定的web url。
因此在代码中的url
变量中,放置了您将提交到的页面的url,这与html表单的action
属性中的url相同,然后代码按预期工作。
进一步阅读:httpcomponents网页。还要注意,大多数Apache开源项目都有一个源代码发行版,其中包含许多示例程序/单元测试,以演示所有不同的功能。
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 如何设置html元素填充的动画
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何编写HTML输入的JS内联
- Dojo不解析自定义小部件的模板html中的小部件声明性
- 使用javascript将动态表从一个html页面打印到另一个html页
- 通过javascript重定向html传递php变量
- 如何使Javascript动态html表及其上的事件
- 在chrome.tabs.onCreated之后加载HTML页面
- 如何在vs2002中调试html页面
- 如何使用javascript或html下载PDF格式的填写表单
- 视频HTML没有'无法在Internet Explorer 11上工作
- HTML表单提交时未执行外部函数
- 如何将输入(type=text)从html表单传递到javascript函数
- 使用angular重定向到html页面
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 在html Select中添加搜索
- 多级HTML表单
- 使用Java以编程方式提交webest 's或blog's html表单