使用Java以编程方式提交webest 's或blog's html表单

submit webiste's or blog's html form programmatically using Java

本文关键字:blog html 表单 Java 提交 webest 使用 编程 方式      更新时间:2023-09-26

我正在尝试使用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开源项目都有一个源代码发行版,其中包含许多示例程序/单元测试,以演示所有不同的功能。