|
Now that you understand how HttpClient is put together, let's consider a simple Swing client designed to talk specifically to the JSP shown in Listing 3-2. Before diving into the code, let's look at how our Swing client works. Swing Client User InterfaceFigure 3-7 shows the initial user interface. Notice the text field at the top, allowing the user to specify a URL, and the two buttons. Figure 3-7. Initial Swing client view.
Clicking the Load button sends a GET request to the specified URL. Figure 3-8 shows the client after clicking the Load button three timesyou'll notice that the counter cookie, displayed at the top of the page (along with the session cookie), is now set to three. The main text area shows the content of the retrieved page, and the bottom bar displays the response code as sent by the server. Figure 3-8. Viewing cookies.
Clicking the Clear button sends a form POST back to the server, as shown in Figure 3-9. The JSP being posted to (see Listing 3-2) is set up to clear the cookies when that form data is received. Figure 3-9. Clearing cookies.
Swing Client CodeNow let's look at the actual code behind this Swing application, starting with Listing 3-3. The main method of interest is the testCookies() method. Depending on the URL retrieved, you may also get cookie data. Listing 3-3. Swing Client GETpackage com.cascadetg.ch03; import org.apache.commons.httpclient.*; import org.apache.commons.httpclient.methods.*; import java.awt.*; public class SwingClient extends javax.swing.JFrame { HttpClient client = new HttpClient(); public SwingClient() { initComponents(); } /** Gets a page via http and displays the cookies and the page */ public void testCookies() { // Sometimes the Internet is slow. this.setCursor(Cursor.WAIT_CURSOR); // We set up a GET request using the URL entered in the URL // textfield. HttpMethod method = new GetMethod(this.urlTextField.getText()); try { client.executeMethod(method); } catch (Exception e) { e.printStackTrace(); } // Set the response label to the returned value. this.responseCodeLabel.setText(method.getStatusCode() + ""); // Now, we start building the text to display. StringBuffer response = new StringBuffer(); // First, we loop through the currently set cookies. Cookie[] cookies = client.getState().getCookies(); for (int i = 0; i < cookies.length; i++) { response.append(cookies[i].getName()); response.append("="); response.append(cookies[i].getValue()); response.append("\n"); } response.append("================================"); response.append("\n"); // Next, we get the response as a String response.append(method.getResponseBodyAsString()); // Finally, we display the response. this.responseText.setText(response.toString()); // Some clean-up. method.releaseConnection(); method.recycle(); // Set the cursor back this.setCursor(Cursor.DEFAULT_CURSOR); } Listing 3-4 shows the POST request, in this case hard-coded to map to the JSP page shown in Listing 3-2. Note that in this case, a simple POST is usedif you want to upload files, for example, you would use the MultipartPostMethod class instead of PostMethod. Also notice the use of the releaseConnection methodwhile not strictly necessary in this trivial app, you need to clean up in this fashion for better performance, and if you later want to switch to a multithreaded client (using the MultiThreadedHttpConnectionManager), cleaning up this way is necessary. Listing 3-4. Swing Client POST/** * We submit a POST request. In this example, we are submitting * a form where we know that a single Submit is the sole * contents of the form. In a "real" browser, you would have * parsed the sent HTML, displayed the user interface, and then * built the response from the displayed user elements. */ public void testPost() { // Sometimes, the Internet is slow. this.setCursor(Cursor.WAIT_CURSOR); try { // Set up a POST retrival HttpMethod method = new PostMethod(this.urlTextField.getText()); // Let's add the form value ((PostMethod)method).addParameter( "Submit", "Clear Cookies!"); // Now, we send the POST client.executeMethod(method); // Here's where we handle the response. Because we've // hard-coded this to work with our form, we know that // we're trying to clear the cookies. StringBuffer response = new StringBuffer(); response.append("Using form submit to clear cookies!"); response.append("\n"); response.append("================================"); response.append("\n"); // Here we get the returned response to display response.append(method.getResponseBodyAsString()); // Now we display it in the Swing UI this.responseText.setText(response.toString()); this.responseCodeLabel.setText( method.getStatusCode() + ""); } catch (Exception e) { e.printStackTrace(); } finally { // Clean up our connection method.releaseConnection(); } this.setCursor(Cursor.DEFAULT_CURSOR); } In the interest of completeness, the final portion of the code, shown in Listing 3-5, creates the Swing graphical user interface for the application.
Listing 3-5. Simple Swing Client Code// Swing user interface variables declaration private javax.swing.JPanel buttonPanel; private javax.swing.JButton clearButton; private javax.swing.JButton goButton; private javax.swing.JLabel responseCodeLabel; private javax.swing.JPanel responseCodePanel; private javax.swing.JTextArea responseText; private javax.swing.JScrollPane responseTextPanel; private javax.swing.JPanel topPanel; private javax.swing.JTextField urlTextField; /** Initializes the Swing user interface. */ private void initComponents() { topPanel = new javax.swing.JPanel(); urlTextField = new javax.swing.JTextField(); buttonPanel = new javax.swing.JPanel(); goButton = new javax.swing.JButton(); clearButton = new javax.swing.JButton(); responseCodePanel = new javax.swing.JPanel(); responseCodeLabel = new javax.swing.JLabel(); responseTextPanel = new javax.swing.JScrollPane(); responseText = new javax.swing.JTextArea(); setTitle("SwingHTTPClient"); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing( java.awt.event.WindowEvent evt) { System.exit(0); } }); topPanel.setLayout(new java.awt.BorderLayout()); urlTextField.setFont(new java.awt.Font("SansSerif", 1, 12)); urlTextField.setText( "http://localhost:8080/ch03/index.jsp"); topPanel.add(urlTextField, java.awt.BorderLayout.CENTER); buttonPanel.setLayout(new java.awt.BorderLayout()); goButton.setText("Load"); goButton .addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt) { testCookies(); } }); buttonPanel.add(goButton, java.awt.BorderLayout.WEST); clearButton.setText("Clear"); clearButton .addActionListener(new java.awt.event.ActionListener() { public void actionPerformed( java.awt.event.ActionEvent evt) { testPost(); } }); buttonPanel.add(clearButton, java.awt.BorderLayout.EAST); topPanel.add(buttonPanel, java.awt.BorderLayout.EAST); getContentPane().add(topPanel, java.awt.BorderLayout.NORTH); responseCodePanel.setLayout(new java.awt.BorderLayout()); responseCodePanel.setBorder( new javax.swing.border.EtchedBorder()); responseCodePanel.setEnabled(false); responseCodeLabel.setText("Result"); responseCodePanel.add(responseCodeLabel, java.awt.BorderLayout.CENTER); getContentPane().add(responseCodePanel, java.awt.BorderLayout.SOUTH); responseTextPanel.setViewportView(responseText); getContentPane().add(responseTextPanel, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width - 400) / 2, (screenSize.height - 300) / 2, 400, 300); } public static void main(String args[]) { new SwingClient().show(); } } |
|