//: c16:POSTtest.java // From Thinking in Java, 2nd Edition // Available at http://www.BruceEckel.com // (c) Bruce Eckel 1999 // Copyright notice in Copyright.txt // An applet that sends its data via a CGI POST // // import javax.swing.*; import java.awt.*; import java.awt.event.*; // Must add this import java.net.*; import java.io.*; public class POSTtest extends JApplet { final static int SIZE = 10; JButton submit = new JButton("Submit"); JTextField[] t = new JTextField[SIZE]; String query = ""; JLabel l = new JLabel(); JTextArea ta = new JTextArea(15, 60); public void init() { Container cp = getContentPane(); JPanel p = new JPanel(); p.setLayout(new GridLayout(t.length + 2, 2)); for(int i = 0; i < t.length; i++) { p.add(new JLabel( "Field " + i + " ", JLabel.RIGHT)); p.add(t[i] = new JTextField(30)); } p.add(l); submit.addActionListener(new AL()); p.add(submit); cp.add("North", p); cp.add("Center", ta); } class AL implements ActionListener { public void actionPerformed(ActionEvent ae) { query = ""; ta.setText(""); // Encode the query from the field data: for(int i = 0; i < t.length; i++) query += "Field" + i + "=" + URLEncoder.encode( t[i].getText().trim()) + "&"; query += "submit=Submit"; // Send the name using CGI's POST process: try { URL u = new URL( getDocumentBase(), "cgi-bin/POSTtest"); URLConnection urlc = u.openConnection(); urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setAllowUserInteraction(false); DataOutputStream server = new DataOutputStream( urlc.getOutputStream()); // Send the data server.writeBytes(query); server.close(); // Read and display the response. You // cannot use // getAppletContext().showDocument(u); // to display the results as a Web page! BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream())); String s; while((s = in.readLine()) != null) { ta.append(s + "\n"); } in.close(); } catch (Exception e) { l.setText(e.toString()); } } } } ///:~