Test servlet communication over the past few days, write a small
Program By reading the configuration information from the properties file, constructing an HTTP header, sending a POST request to the servlet, and receiving the servlet results, the following shows the approximate structure of the program:
Import java.net .*;
Import java. Io .*;
public class testpost {
Public static void main () {
URL url = NULL;
httpurlconnection conn = NULL;
try {
url = new URL ("http: // localhost/projectname/servletname"); // construct this URL object, the parameter is the servlet address you want to communicate with. In actual testing, this URL can be obtained from the properties file to increase flexibility
conn = (httpurlconnection) URL. openconnection (); // open and create a connection object
Conn. setrequestmethod ("Post"); // set the request method to post
Conn. setdooutput (true); // It must be set to true because data needs to be sent.
// Set the HTTP header below
Conn. setrequestproperty ("Content-Type", "multipart/form-data; boundary = bounday ---");
Conn. setrequestproperty ("cache-control", "No-Cache ");
.......
// Send data
Outputstream Buf = conn. getoutoutstream ();
Buf = new bufferedoutputstream (BUF );
Outputstreamwriter out = new outputstreamwriter (BUF );
Out. Write ("here is the data to be transferred ");
// For example, the following format. Of course, this is the prescribed format, which can be set in the configuration file and then read
// Bounday ---
// Content-Disposition: Form-data; name = "testrequestheader"
// Data = aabbccddeeffgghh
// -- Bounday ---
Out. Flush (); // This Must Be
Out. clost ();
// Receive data
Inputstream in = conn. getinputstream ();
In = new bufferedoutputstream (BUF );
Reader RDATA = new inputstreamreader (in );
int C;
system. out. println ("================================= result ====================== ============ ");
while (C = RDATA. read ())! =-1)
system. out. print (char) C);
system. out. println ("========================================== ================ ");
in. close ();
}catch (exception e) {
E. printstacktrace ();
}finally {
}< BR >}