Java Form Submit


เตรียม server (เขียนด้วย php)

<?php
$hidden='';
$result_hidden='hidden="hidden"';
$action='"form.php"';
$number1= $_POST["number1"]; 
$number2= $_POST["number2"];
if( ! is_null($number1) && ! is_null($number2)) {
	$hidden='hidden="hidden"';
	$result_hidden='';
}

?>
<!DOCTYPE HTML>

<html lang="en">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>Form</title>
	<meta name="author" content="Mossila">
	<!-- Date: 2011-06-28 -->
	
</head>
<body>
	<div id="inputform" <?=$hidden?>>
		<form action=<?=$action?> method="post">
			<label for="number1" >number1</label>
			<input type="text" name="number1" id="number1" required="required" />
			<br />
			<label for="number2">number2</label>
			<input type="text" name="number2" id="number2" required="required"  />
			<br />
			<input type="submit" value="Submit" />
		</form>
	</div>
	<div id="result" <?=$result_hidden?>>
		<p>number1=<?=$number1?><br />
		   number2=<?=$number2?><br />
		   number1+number2=<?=$number1+$number2?>
		</p>
	</div>
</body>


</html>
<?php //ถ้าเป็น sourcecode php จงเปิด php ไว้ท้ายไฟล์เถิดจะเกิดผล เว้นวรรคไว้ซักหน่อยด้วย 


ต่อด้วย java ตัวที่จะทำ form submit
โดยตัวนี้เป็นแค่ Console Application นะจ๊ะ

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author mossila
 */
public class Client {

    
    private static String resultIdentifier = "number1+number2=";
    private static String endResultIdentifier = "</p>";
    private static String baseUrl = 
            "http://localhost/~mossmahidol/Network/week2/";
    private static String action = "form.php";

    public static void main(String[] args) {

        HashMap<String, String> data = new HashMap<String, String>();
        loadConfig();
        data.put("number1", readLine("number1:"));
        data.put("number2", readLine("number2:"));
        try {
            doSubmit(baseUrl + action, data);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }

    private static void 
            doSubmit(String url, HashMap<String, String> data) 
            throws UnsupportedEncodingException, IOException {
        URL siteUrl = new URL(url);
        HttpURLConnection conn = 
                (HttpURLConnection) siteUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);

        DataOutputStream out = 
                new DataOutputStream(conn.getOutputStream());

        Set<String> keys = data.keySet();
        Iterator<String> keyIter = keys.iterator();
        String content = "";
        for (int i = 0; keyIter.hasNext(); i++) {
            String key = keyIter.next();
            if (i != 0) {
                content += "&";
            }
            content += key + "=" + 
                    URLEncoder.encode(data.get(key), "UTF-8");
        }
        //System.out.println(content);
        out.writeBytes(content);
        out.flush();
        out.close();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
        String line = "";
        while ((line = in.readLine()) != null) {
            if (line.contains(resultIdentifier)) {
                System.out.println("result=" + line.substring(
                     line.indexOf(resultIdentifier) + 
                     resultIdentifier.length(),
                     line.indexOf(endResultIdentifier)).trim());
            }

        }
        in.close();
    }

    private static void loadConfig()  {
        try {
            FileInputStream fstream = new FileInputStream("config.txt");
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = 
                    new BufferedReader(new InputStreamReader(in));
            String strLine;
            //Read File Line By Line
            while ((strLine = br.readLine()) != null) {
	        //assign config value to program
                if(strLine.startsWith("base_url=")) {
                    baseUrl = strLine.substring(
                            strLine.indexOf("base_url=") +
                            "base_url=".length());
                }
                if(strLine.startsWith("action=")) {
                    action = strLine.substring(
                            strLine.indexOf("action=") +
                            "action=".length());
                }
                System.out.println(strLine);
            }
        }catch(FileNotFoundException ex) {
            Logger.getLogger(Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
        catch (IOException ex) {
            Logger.getLogger(Client.class.getName())
                    .log(Level.SEVERE, null, ex);
        }
    }
     private static String readLine(CharSequence label) {
        System.out.print(label);
        BufferedReader br = 
                new BufferedReader(new InputStreamReader(System.in));

        String line = "";
        try {
            line = br.readLine();
        } catch (IOException ioe) {
            System.out.println(
                "IO error trying to read your input!" 
                + ioe.getMessage());
            System.exit(1);
        }
        return line;
    }
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s