使用 Java 将数据发送到本地托管网站上的表单

发布于 2024-10-23 13:45:13 字数 1062 浏览 1 评论 0原文

我有一个 Java 程序,可以从数据库中检索内容。
现在我的程序中有一个表单,我想要做的是,按一下按钮,从数据库检索到的一些字符串(文本)内容应该发送到我在本地托管的网站。如此发送的内容应在刷新时显示在网站上。

有人可以指导我如何实现这一目标(发送要在网站上显示的数据)吗? 如果您能展示一些示例片段或给我一些可以提供帮助的教程的参考,我将不胜感激。

---- 好吧,我找到了一个应该执行此操作的代码片段的链接,但我现阶段无法理解该代码片段到底是如何工作的......有人可以指导我更好地了解这一点吗? 这是代码

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

I have a program in Java where I retrieve contents from a database.
Now I have a form in the program, and what I want to do is, on the press of a button, some string (text) content retrieved from the database, should be sent over to a website that I'm hosting locally. The content so sent, should be displayed on the website when refreshed.

Can someone guide me as to how I can achieve this (the sending of data to be displayed over the website)?
Will appreciate a lot, if you could kindly show some sample snippets or give me a reference to some tutorial that can help.

---- Okay so i found a link to a snippet that's supposed to do this, but im unable to understand at this stage as to how exactly this snippet works...can someone please guide me into knowing this better ?
here's the code

try {
    // Construct data
    String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
    data += "&" + URLEncoder.encode("key2", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");

    // Send data
    URL url = new URL("http://hostname:80/cgi");
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        // Process line...
    }
    wr.close();
    rd.close();
} catch (Exception e) {
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酒儿 2024-10-30 13:45:14

最大的问题是如何验证从 Java 程序到网站的“更新”?

您可以轻松地在您的网站上编写一个处理程序,例如“/update”,它将 POST 正文(或请求参数的值)保存到文件或其他持久存储中,但您如何确定只有您自己才能执行此操作? > 可以设置该值,而不是任何发现它的人吗?

The big question is how will you authenticate the "update" from your Java program to your website?

You could easily write a handler on your website, say "/update" which saves the POST body (or value of a request parameter) to a file or other persistent store but how will you be sure that only you can set that value, instead of anybody who discovers it?

疯到世界奔溃 2024-10-30 13:45:13

我不确定如何存储和管理任何记录,但从 Java 中,您可以将 HTTP Post 发送到 URL(在您的情况下 http ://localhost/,可能)。

看看 http://www.exampledepot.com/egs/java.net /post.html 了解如何执行此操作的代码片段。

然后,您的网站可以将收到的信息存储在数据库中,并在您刷新时显示它。

更新这里是函数

只是一个方面,这绝不是最好的方法,我不知道它是如何扩展的,但对于简单的解决方案,这在过去对我有用.

     /**
     * Posts a Set of forms variables to the Remote HTTP Host
     * @param url The URL to post to and read
     * @param params The Parameters to post to the remote host
     * @return The Content of the remote page and return null if no data was returned
     */
    public String post(String url, Map<String, String> params) {

        //Check if Valid URL
        if(!url.toLowerCase().contains("http://")) return null;

        StringBuilder bldr = new StringBuilder();

        try {
            //Build the post data
            StringBuilder post_data = new StringBuilder();

            //Build the posting variables from the map given
            for (Iterator iter = params.entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                String value = (String)entry.getValue();

                if(key.length() > 0 && value.length() > 0) {

                    if(post_data.length() > 0) post_data.append("&");

                    post_data.append(URLEncoder.encode(key, "UTF-8"));
                    post_data.append("=");
                    post_data.append(URLEncoder.encode(value, "UTF-8"));
                }
            }

            // Send data
            URL remote_url = new URL(url);
            URLConnection conn = remote_url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(post_data.toString());
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = rd.readLine()) != null) {
                bldr.append(inputLine);
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            //Handle Error
        }

        return bldr.length() > 0 ? bldr.toString() : null;
    }

然后您可以按如下方式使用该函数:

        Map<String, String> params = new HashMap<String, String>();
        params.put("var_a", "test");
        params.put("var_b", "test");
        params.put("var_c", "test");
        String reponse = post("http://localhost/", params);
        if(reponse == null) { /* error */ }
        else {
            System.out.println(reponse);
        }

I'm not sure on how you store and manage any of the records but from Java you can send a HTTP Post to the Url (In your case http://localhost/, probably).

Have a look at http://www.exampledepot.com/egs/java.net/post.html for a snippet on how to do this.

Your Website could then store the received information in a database and display it when you refresh.

Update heres the function

Just a side not this is by no means the best way to do this and I have no idea on how this scales but for simple solutions this has worked for me in the past.

     /**
     * Posts a Set of forms variables to the Remote HTTP Host
     * @param url The URL to post to and read
     * @param params The Parameters to post to the remote host
     * @return The Content of the remote page and return null if no data was returned
     */
    public String post(String url, Map<String, String> params) {

        //Check if Valid URL
        if(!url.toLowerCase().contains("http://")) return null;

        StringBuilder bldr = new StringBuilder();

        try {
            //Build the post data
            StringBuilder post_data = new StringBuilder();

            //Build the posting variables from the map given
            for (Iterator iter = params.entrySet().iterator(); iter.hasNext();) {
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                String value = (String)entry.getValue();

                if(key.length() > 0 && value.length() > 0) {

                    if(post_data.length() > 0) post_data.append("&");

                    post_data.append(URLEncoder.encode(key, "UTF-8"));
                    post_data.append("=");
                    post_data.append(URLEncoder.encode(value, "UTF-8"));
                }
            }

            // Send data
            URL remote_url = new URL(url);
            URLConnection conn = remote_url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(post_data.toString());
            wr.flush();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = rd.readLine()) != null) {
                bldr.append(inputLine);
            }
            wr.close();
            rd.close();
        } catch (Exception e) {
            //Handle Error
        }

        return bldr.length() > 0 ? bldr.toString() : null;
    }

You would then use the function as follows:

        Map<String, String> params = new HashMap<String, String>();
        params.put("var_a", "test");
        params.put("var_b", "test");
        params.put("var_c", "test");
        String reponse = post("http://localhost/", params);
        if(reponse == null) { /* error */ }
        else {
            System.out.println(reponse);
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文