The following code shows you how to send and receive CGI messages from a Java application:
import java.net.*;
import java.io.*;
class POSTrequest{
URL url=null;
URLConnection URLcon=null;
OutputStreamWriter OSW=null;
BufferedReader BR=null;
PrintStream PS=null;
public void GetReady()
{
try {
//it may be any other CGI
url=new URL("http://ludlow.dns2go.com/cgi-bin/plot/cut_basemap.pl");
URLcon=url.openConnection();
URLcon.setDoInput(true);
URLcon.setDoOutput(true);
//disable caching
URLcon.setUseCaches(false);
URLcon.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
SendRequest();
}catch(MalformedURLException e)
{System.out.println("Error 1:"+e.getMessage());
}catch(IOException e)
{System.out.println("Error 2:"+e.getMessage());
}catch(ClassCastException e)
{System.out.println("Error:"+e.getMessage());}
}
void SendRequest()throws IOException
{
OSW=new OutputStreamWriter(URLcon.getOutputStream());
String request=URLEncoder.encode("LONGDEG","UTF-8")+
"="+URLEncoder.encode
("76","UTF-8")+"&"+URLEncoder.encode("LONGMIN","UTF-8")+
"="+URLEncoder.encode("37.3","UTF-8");
request+="&"+URLEncoder.encode("LATDEG","UTF-8")+
"="+URLEncoder.encode("2","UTF-
")+"&"+URLEncoder.encode("LATMIN","UTF-8")+"="+URLEncoder.encode("34.84","UTF-8");
request+="&"+URLEncoder.encode("CROPSIZE","UTF-8")
+"="+URLEncoder.encode
("20x15","UTF-8")+"&"+URLEncoder.encode("OUTPUTSIZE","UTF-8")+
"="+URLEncoder.encode
("8x6","UTF-8");
OSW.write(request);
OSW.flush();
OSW.close();
GetAnswer();
}
void GetAnswer() throws IOException
{
//get the answer in a HTML file
BR=new BufferedReader(new InputStreamReader(URLcon.getInputStream()));
PS=new PrintStream(new FileOutputStream(".\\output.html"));
String answer;
while (null!=((answer=BR.readLine())))
{
System.out.println (answer);
PS.println(answer);
}
BR.close();
PS.close();
}
public void POSTanswer()
{
try {
//view answer
String command = "C:\\Program Files\\Mozilla Firefox\\firefox.exe
file:///D:/JEditor/programe/network/output.html";
Process child = Runtime.getRuntime().exec(command);
}catch(IOException e)
{System.out.println("Error 5:"+e.getMessage());}
}
}
public class POST{
public static void main(String[] args)
{
POSTrequest t=new POSTrequest();
t.GetReady();
t.POSTanswer();
}
}