Wednesday, December 01, 2004

Post Form Data to CGI (Java 1.5)


//This one uses java 1.5, the new Generics method.
package uhn;

import java.util.Stack;
import java.net.*;
import java.io.*;

/**
* Title: FormPost
* Description: Post form to CGI server on the net
* Copyright: Copyright (c) 2003
* Company: UHN
* @author Zhibin Lu
* @version 1.0
*/

public class FormPost {
private URLConnection urlConn;
private OutputStreamWriter printout;
private BufferedReader input;
private Stack para;

/** Constructor of the class
* @param url URL address to post form (action)
* @param parameters parameters to pass to the server
*/
public FormPost(String url, Stack parameters) {
para = parameters;
try {
urlConn = (new URL(url)).openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy.uhnres.utoronto.ca", 3128)));
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.setRequestProperty("user-agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5) Gecko/20041107 Firefox/1.0)");
urlConn.setRequestProperty("accept", "text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
}
catch (Exception e){
System.err.println("Constructor of FormPost: " + e);
urlConn = null;
}
}

/** Connect to the web CGI server
* @return BufferedReader to read the result from CGI server
*/
public BufferedReader connect() {
try {
printout = new OutputStreamWriter(urlConn.getOutputStream (), "ISO-8859-1");
if (!para.empty()) {
printout.write((String) para.pop());
}
while (!para.empty()) {
printout.write("&" + para.pop());
}
printout.flush ();
printout.close ();

input = new BufferedReader(new InputStreamReader(urlConn.getInputStream ()));
}
catch (IOException e) {
System.err.println("FormPost connect: " + e);
input = null;
}
finally {
return input;
}
}

/** Close the connect to the CGI server */
public void close() {
try {
input.close();
}
catch (IOException e) {
System.err.println("FormPost close: " + e);
}
}
public static void main(String[] args) throws IOException {
FormPost form;
Stack parameters = new Stack();
String line;

parameters.push("FORM=MSNH");
parameters.push("q=test");

form = new FormPost("http://search.msn.com/results.aspx", parameters);
BufferedReader in = form.connect();
while ((line=in.readLine()) != null) {
System.out.println(line);
}
in.close(); form.close();
}

}///:~

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home