import java.net.*; import java.io.*; /** * CGI interface allows a java program to send POST-style * messages to a CGI on a server. * @author J. Dalbey * @version 2/28/06 * Here is an example perl CGI: *
#!/usr/bin/perl
# this is a perl CGI that will accept a POST request
# and append the info to a text file.
 
open(OUT, ">> LobbyStatus.txt");
print "content-type: text/plain\n\n";
 
# write the POST data to the file
while (<>) {
    print OUT $_;
    print OUT "\n";
}
close (OUT);
 
#Echo an acknowledgement to the sender
print "OK";
exit 0;
  * 
* */ public class CGIinterface { /** The domain to connect to: e.g., www.calpoly.edu */ private String domain; /** The path to the CGI (relative to the domain) */ private String cgiName; /** * Construct a CGI interface. * @param domain the domain where the server resides, e.g., www.csc.calpoly.edu * @param cgiName the path to the CGI (relative to the domain), e.g., /~jstudent/mycgi.pl */ public CGIinterface (String domain, String cgiName) { this.domain = domain; this.cgiName = cgiName; } /** Send a message to the CGI * @param message A string to be sent to the cgi containing POST data */ public void sendPostData(String message) { /* Open the URL using openConnection(). As this is using a CGI POST to send the data (as opposed to a GET in which the data would be appended to the end of the URL i.e. http://www.yourdomain.com/cgi-bin/writeit?myinfo), we are defining the Content-type to be text/plain. */ URL url; URLConnection con = null; try { url = new URL("http",domain,cgiName); con = url.openConnection(); } catch (MalformedURLException ex){ex.printStackTrace();} catch (IOException ex) {ex.printStackTrace();} // Prepare the connection con.setDoOutput(true); con.setDoInput(true); con.setUseCaches(false); con.setRequestProperty("Content-type", "text/plain"); con.setRequestProperty("Content-length", message.length()+""); // Send the message over the connection try { PrintStream out = new PrintStream(con.getOutputStream()); out.print(message); out.flush(); out.close(); // Read and swallow anything the server sends back to us. DataInputStream in = new DataInputStream(con.getInputStream()); String s; while ((s = in.readLine()) != null) { //System.out.println(s); } in.close(); } catch (IOException ex) {ex.printStackTrace();} } /** a local main for unit testing */ public static void main(String args[]) { String lobby_info = "Sun Feb 26 15:55:40 PST 2006 129.65.111.22 Need 3 players"; CGIinterface myCGI = new CGIinterface("www.csc.calpoly.edu", "/~jdalbey/Public/LobbyUpdate.pl"); myCGI.sendPostData(lobby_info); } }