【问题标题】:Unable to send a post form in Java无法在 Java 中发送帖子表单
【发布时间】:2018-02-09 21:37:40
【问题描述】:

代码的目的是将参数插入表单,然后提交表单,表单又将数据输入 MySQL 数据库。问题是该方法不发布数据。我不确定我做错了什么,我已经查看了很多关于此的问题,但似乎没有任何效果。

这是表格。

<form action="http://localhost/Documents/dataadded.php" method="post">

<b>Add a New Data</b>

<p>Email Address:
<input type="text" name="email_address" size="30" value="" />
</p>

<p>Email Pass:
<input type="text" name="email_pass" size="30" value="" />
</p>

<p>
<input type="submit" name="submit" value="Send" />
</p>

</form>

这里是 Java 代码。

public static void main(String[] args) {


    String key1 = "email_address";
    String key2 = "email_pass";
    String key3 = "submit";

    String param1 = "testemail@gmail.com";
    String param2 = "password123";
    String param3 = "Send";
    try {
        URL website = new URL("http://localhost/Documents/added.php");

        Map<String,String> arguments = new LinkedHashMap<>();
        arguments.put(key1, param1);
        arguments.put(key2, param2);
        arguments.put(key3, param3);

        StringJoiner sj = new StringJoiner("&");
        for(Map.Entry<String,String> entry : arguments.entrySet())
            sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "=" 
                 + URLEncoder.encode(entry.getValue(), "UTF-8"));
        byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
        int length = out.length;

        HttpURLConnection connection =  (HttpURLConnection) website.openConnection(); 
        connection.setRequestMethod("POST");
        connection.setFixedLengthStreamingMode(length);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        connection.setDoOutput(true);
        connection.getOutputStream().write(out);


        System.out.println(sj.toString());

        InputStream response = connection.getInputStream();

        @SuppressWarnings("resource")
        Scanner scan = new Scanner(response);
        String responsebody = scan.useDelimiter("\\A").next();
        System.out.println(responsebody);



    } catch (IOException e) {

        e.printStackTrace();
    }

}

如果有人能阐明代码有什么问题,我们将不胜感激。

【问题讨论】:

  • PHP是如何参与的?
  • 当表单提交时,数据被传递给localhost/Documents/dataadded.php,它有PHP代码处理数据并将其添加到数据库中。
  • @C.Trant 但这实际上与您的问题有关吗?你如何处理数据似乎无关紧要,你的问题是数据的传递
  • Java代码中的URL与表单中的不同。
  • 是的,我的错,我发的第一篇文章,它建议了 php 标签和其他标签,所以我点击了它们。

标签: java http httpurlconnection


【解决方案1】:

您必须先刷新 OutputStream,然后才能打开 InputStream。下面是我创建的用于执行 POST 请求的方法。

private String doPost(String urlString, LinkedHashMap<String, String> params) throws Exception {
    //...make the content
    StringBuilder content = new StringBuilder();
    //...append params
    boolean first = true;
    for (Map.Entry<String, String> entry : params.entrySet()) {
        if (!first) {
            content.append("&");
        } else {
            first = false;
        }
        content.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), charset));
    }
    //... send POST request
    URL url = new URL(urlString);
    HttpURLConnection con;
    con = (HttpURLConnection) url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    try (OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), charset)) {
        writer.write(content.toString());
        writer.flush();
    }
    //...get response
    try (Scanner s = new Scanner(con.getInputStream(), charset)) {
        String resp = s.useDelimiter("\\A").hasNext() ? s.next() : "";
        return resp;
    }
}

【讨论】:

  • try-with-resources 关闭输出流,关闭输出流会刷新它,你当然不应该在循环内刷新..
  • 您的回答表明您必须冲洗。你没有。
  • @EJP 你在说什么循环?我承认关闭确实刷新,但是需要进行刷新,问题是您是否希望通过关闭为您完成它,或者您是否想明确说明它。我选择明确说明。
猜你喜欢
  • 2013-03-16
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 2017-05-16
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
相关资源
最近更新 更多