简体   繁体   English

无法使用Java发送帖子表单

[英]Unable to send a post form in Java

The objective of the code is to insert the parameters into the form then submits the form which in turn enters the data into a MySQL database. 代码的目标是将参数插入表单然后提交表单,然后将表单数据输入MySQL数据库。 The problem is that the method doesn't post the data. 问题是该方法不发布数据。 I'm not sure what I'm doing wrong, I've looked at so many questions regarding this but nothing seems to work. 我不确定我做错了什么,我已经看了很多这方面的问题,但似乎没什么用。

Here is the form. 这是表格。

<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>

Here is the Java code. 这是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();
    }

}

If anyone could shed some light on what's wrong with the code, it will be greatly appreciated. 如果有人能够解释代码的错误,我们将不胜感激。

You have to flush the OutputStream before you can open the InputStream. 您必须先刷新OutputStream,然后才能打开InputStream。 Below is the method I created to do POST requests. 下面是我创建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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM