Arun
Arun

Reputation: 11

Using Java to send data to a form on a website hosted locally

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) {
}

Upvotes: 0

Views: 4959

Answers (2)

Johann du Toit
Johann du Toit

Reputation: 2667

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);
        }

Upvotes: 1

maerics
maerics

Reputation: 156434

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?

Upvotes: 0

Related Questions