8.客户端使用URL方法调用服务器的CGI
(一)客户(浏览器)端程序:
import https://www.wendangku.net/doc/4318556337.html,.*;
import java.io.*;
public class URLBrowser {
public static void main(String[] args) {
try {
String host = “localhost”;
String port = “8080”;
String fileName = “cgi-bin/Form.cgi”;
String HTTPString =
"http://"+host+":"+port+"/"+fileName;
URL theURL = new URL(HTTPString);//封装成URL对象
InputStream inStream = theURL.openStream( );
BufferedReader input =
new BufferedReader
(new InputStreamReader(inStream));//解析成输入流String response;
response = input.readLine();
// read and display one line at a time
while (response != null) {
System.out.println(response);
response = input.readLine();
} //end while
}
catch (Exception ex) {
System.out.println("ERROR : " + ex) ;
ex.printStackTrace(System.out);
}
}// end main
} //end class
(二)服务端流程:
(1)为Tomcat配置CGI服务
(2)编写CGI代码-- Form.cgi
#include
#ifndef NO_STDLIB_H
#include
#else
char *getenv();
#endif
typedef struct {
char name[128];
char val[128];
} entry;
void getword(char *word, char *line, char stop);
char x2c(char *what);
void unescape_url(char *url);
void plustospace(char *str);
main(int argc, char *argv[]) {
entry entries[10000];
register int x,m=0;
char *cl;
printf("Content-type: text/html%c%c",10,10);
if(strcmp(getenv("REQUEST_METHOD"),"GET")) {
printf("This script should be referenced
with a METHOD of GET.%c", 13);
exit(1);
}
cl = getenv("QUERY_STRING");
if(cl == NULL) {
printf("No query information to decode.%c",13);
exit(1);
}
for(x=0;cl[0] != '\0';x++) {
m=x;
getword(entries[x].val,cl,'&');
plustospace(entries[x].val);
unescape_url(entries[x].val);
getword(entries[x].name,entries[x].val,'=');
}
printf("
");printf("
printf("
printf(
"You submitted the following name/value pairs:",
"
%c",10);
printf("
for(x=0; x <= m; x++)
printf("
%s = %s
%c",entries[x].name, entries[x].val,10);
printf("");
printf("