0

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) {
}
5
  • Use AJAX to accomplish this task.,. Tutorial/Reference for ajax.. jaxtut.com Commented Mar 18, 2011 at 7:30
  • "Use Ajax" is not the solution to every problem involving sending data across a network. Commented Mar 18, 2011 at 7:33
  • @David:- ya, but ajax can fulfill given requirement.,right? Commented Mar 18, 2011 at 7:35
  • No. Since it sounds like the client is a Java application, not a web browser. Even if it could, then "Use Ajax" is like answering "How do I get from London to Manchester?" with "Drive" — the route is usually the bit that matters. Commented Mar 18, 2011 at 7:38
  • Technically "use the internet" fulfills the "given requirement". I think he was looking for something slightly more useful and specific. Commented Jun 12, 2012 at 16:41

2 Answers 2

1

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);
        }
Sign up to request clarification or add additional context in comments.

3 Comments

Hi @Johann I did look at the snippet ,can you kindly give me a overview as to how the three functional parts i.e. the data construct, write stream and read stream work in conjunction to send my custom data ? also where must i place the reference for my custom string data in the snippet ?
Hi, I've got a nifty little function that I use normally to accomplish sending form and returning a string. Will update when I get to my pc. And the process is relatively easy. You construct the string that will contain your form data (Which is normally formatted as "var=test&var_second=test&var_three=text"). The string is then send to the url and your read any output that the url gives you. (Maybe a "true" if the data was succesfully received or a "false" if their was a error).
Thank you @Johann nice, im able to relate that to the snippet that you referred to me, will look forward for your update whenever you can get to your pc , thanks !
0

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.