Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
452
Chapter 17 Using Applets As Servlet Front Ends
5. Create a 
ByteArrayOutputStream
 to buffer the data that 
will be sent to the server. The purpose of the 
ByteArray 
OutputStream
 here is the same as it is with the persistent 
(keep alive) HTTP connections shown in Section 7.4   to 
determine the size of the output so that the 
Content Length
header can be set. The 
ByteArrayOutputStream
 constructor 
specifies an initial buffer size, but this value is not critical 
since the buffer will grow automatically if necessary.
ByteArrayOutputStream byteStream =
new ByteArrayOutputStream(512);
6. Attach an output stream to the 
ByteArrayOutputStream
. 
Use a 
PrintWriter
 to send normal form data. To send serial 
ized data structures, use an 
ObjectOutputStream
 instead.
PrintWriter out = new PrintWriter(byteStream, true);
7. Put the data into the buffer. For form data, use 
print
. For 
high level serialized objects, use 
writeObject
.
String val1 = URLEncoder.encode(someVal1);
String val2 = URLEncoder.encode(someVal2);
String data = "param1=" + val1 +
"¶m2=" + val2; // Note '&'
out.print(data);
// Note print, not println
out.flush(); // Necessary since no println used
8. Set the 
Content Length
 header. This header is required for 
POST
 data, even though it is unused with 
GET
 requests.
connection.setRequestProperty
("Content Length", String.valueOf(byteStream.size()));
9. Set the 
Content Type
 header. Netscape uses 
multi 
part/form data
 by default, but regular form data requires a 
setting of 
application/x www form urlencoded
, which is 
the default with Internet Explorer. So, for portability you should 
set this value explicitly when sending regular form data. The 
value is irrelevant when sending serialized data.
connection.setRequestProperty
("Content Type", "application/x www form urlencoded");
Home page for this book: www.coreservlets.com; Home page for sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.






footer




 

 

 

 

 Home | About Us | Network | Services | Support | FAQ | Control Panel | Order Online | Sitemap | Contact

jsp web hosting

 

Our partners: PHP: Hypertext Preprocessor Best Web Hosting Java Web Hosting Jsp Web Hosting Cheapest Web Hosting

Visionwebhosting.net Business web hosting division of Web Design Plus. All rights reserved