001: /*
002: * This is a very simple example of how to use the HTTPClient package in an
003: * Applet. It just POSTs a request to a cgi-script on the server when you
004: * hit the 'Doit' button, and then displays the returned headers and data in
005: * a text window.
006: */
007:
008: package HTTPClient.doc;
009:
010: import java.applet.*;
011: import java.awt.*;
012: import HTTPClient.*;
013:
014: public class HTTPClientExample extends Applet implements Runnable {
015: private HTTPConnection con;
016: private HTTPResponse rsp = null;
017: private String script = "/cgi-bin/my_script.cgi";
018:
019: private String disp = "";
020: private Thread thread = null;
021: private boolean done = false;
022: private TextArea text;
023:
024: public void init() {
025: /* setup a text area and a button */
026:
027: setLayout(new BorderLayout());
028:
029: add("Center", text = new TextArea(60, 60));
030: text.setEditable(false);
031:
032: add("South", new Button("Doit"));
033:
034: /* get an HTTPConnection */
035:
036: try {
037: con = new HTTPConnection(getCodeBase());
038: } catch (Exception e) {
039: disp = "Error creating HTTPConnection:\n" + e;
040: repaint();
041: return;
042: }
043: }
044:
045: public void start() {
046: /* run the http request in a separate thread */
047:
048: if (thread == null) {
049: done = false;
050: thread = new Thread(this );
051: thread.start();
052: }
053: }
054:
055: public void run() {
056: try {
057: while (true) {
058: /* wait for the button to be pressed */
059:
060: waitForDoit();
061: if (done)
062: break;
063:
064: /* POST something to the script */
065:
066: disp = "POSTing ...";
067: repaint();
068: rsp = con.Post(script, "Hello World again");
069: repaint();
070: }
071: } catch (Exception e) {
072: disp = "Error POSTing: " + e;
073: e.printStackTrace();
074: repaint();
075: }
076: }
077:
078: private synchronized void waitForDoit() {
079: try {
080: wait();
081: } catch (InterruptedException ie) {
082: }
083: }
084:
085: private synchronized void notifyDoit() {
086: notify();
087: }
088:
089: public void stop() {
090: if (thread != null) {
091: done = true;
092: notifyDoit();
093: thread = null;
094: }
095: }
096:
097: public boolean action(Event evt, Object obj) {
098: if (obj.equals("Doit")) {
099: notifyDoit(); // tell request thread to do the request
100: return true;
101: }
102:
103: return super .action(evt, obj);
104: }
105:
106: public void paint(Graphics g) {
107: text.setText(disp + "\n");
108:
109: if (rsp == null)
110: return;
111:
112: try {
113: text.appendText("\n---Headers:\n" + rsp.toString());
114: text.appendText("\n---Data:\n"
115: + new String(rsp.getData(), 0) + "\n");
116: } catch (Exception e) {
117: text.appendText("\n---Got Exception:\n" + e + "\n");
118: }
119: }
120: }
|