📄 aug01_ericg.txt
字号:
it:
int len = request.getContentLength();
ServletInputStream in = request.getInputStream();
if( len != -1 ){
// read in a fixed number of bytes
} else {
// read until EOF
}
After processing the input, the servlet should set the response
code and the content type:
response.setStatus( Response.SC_OK );
response.setContentType( "application/octet-stream" );
Of course, if an error occurs, the servlet calls sendError and
does not send any response data. Otherwise, the servlet sets the
content length (if known) and sends the data:
byte[] data = ....; // the data to send
response.setContentLength( data.length );
ServletOutputStream out = response.getOutputStream();
out.write( data );
The servlet then returns from the doPost method, and the web
server sends the response to the client, which processes it as
discussed above.
This Tech Tip ends with a complete client-server example that
shows a MIDlet communicating with a servlet. The example uses the
HttpConnectionHelper class previously described.
Let's start with the servlet code, since it's simpler. The
servlet takes a string sent to it by the client, converts it to
uppercase and sends it back as a series of tokens (words):
package j2me.techtips;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* A simple example of a servlet that responds to an
* input stream sent to it by a MIDP client.
*/
public class SampleServer extends HttpServlet {
public void doPost( HttpServletRequest request,
HttpServletResponse response )
throws IOException, ServletException {
// Get the input stream and read the data...
ServletInputStream in =
request.getInputStream();
DataInputStream din =
new DataInputStream( in );
String text = din.readUTF();
din.close();
// Do something with the data. In this case
// make the string upper case and split it
// into tokens.
text = text.toUpperCase();
StringTokenizer tok = new StringTokenizer(
text );
Vector v = new Vector();
while( tok.hasMoreTokens() ){
v.addElement( tok.nextToken() );
}
// Form a response: send back the # of strings
// followed by each string in turn.
ByteArrayOutputStream bout =
new ByteArrayOutputStream();
DataOutputStream dout =
new DataOutputStream( bout );
int size = v.size();
dout.writeInt( size );
for( int i = 0; i < size; ++i ){
dout.writeUTF( (String) v.elementAt( i ) );
}
byte[] data = bout.toByteArray();
// Set the response headers and data...
response.setContentType(
"application/octet-stream" );
response.setContentLength( data.length );
response.setStatus( response.SC_OK );
OutputStream out = response.getOutputStream();
out.write( data );
out.close();
}
}
The MIDP client consists of an entry form where the user can type
in some text and press the "Send" button to have it delivered to
the server for processing:
package j2me.techtips;
import java.io.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
/**
* Sample client that shows how to communicate with
* a servlet running on a web server. Asks for a string
* from the user and sends it to the server, which then
* makes it upper case, and returns it as a series of
* tokens.
*/
public class SampleClient extends MIDlet
implements CommandListener {
// The URL to connect to... change as appropriate...
private static String url =
"http://localhost:8080/servlet/j2me.techtips.SampleServer";
private Display display;
private Command exitCommand =
new Command( "Exit", Command.EXIT, 1 );
private Command okCommand =
new Command( "OK", Command.OK, 1 );
private Command sendCommand =
new Command( "Send", Command.OK, 1 );
private TextBox entryForm;
public SampleClient(){
}
protected void destroyApp( boolean unconditional )
throws MIDletStateChangeException {
exitMIDlet();
}
protected void pauseApp(){
}
protected void startApp()
throws MIDletStateChangeException {
if( display == null ){ // first time called...
initMIDlet();
}
}
private void initMIDlet(){
display = Display.getDisplay( this );
entryForm = new EntryForm();
display.setCurrent( entryForm );
}
public void exitMIDlet(){
notifyDestroyed();
}
public void commandAction(
Command c, Displayable d ){
if( c == sendCommand ){
StatusForm f =
new StatusForm( entryForm.getString() );
display.setCurrent( f );
f.start();
} else if( c == okCommand ){
display.setCurrent( entryForm );
} else {
exitMIDlet();
}
}
// The text entry form...
class EntryForm extends TextBox {
EntryForm(){
super( "Enter some text", "", 80, 0 );
addCommand( exitCommand );
addCommand( sendCommand );
setCommandListener( SampleClient.this );
}
}
// A status for for displaying messages as the data
// is sent...
class StatusForm extends Form
implements Runnable,
HttpConnectionHelper.Callback {
StatusForm( String text ){
super( "Status" );
// Convert the string into a byte array.
// Doing it this way ensures that the
// characters retain their encoding.
try {
ByteArrayOutputStream bout =
new ByteArrayOutputStream();
DataOutputStream dout =
new DataOutputStream( bout );
dout.writeUTF( text );
data = bout.toByteArray();
dout.close();
}
catch( IOException e ){
// should handle this....
}
}
// Updates the display.
void display( String text ){
if( message == null ){
message = new StringItem( null, text );
append( message );
} else {
message.setText( text );
}
}
// Done.
void done( String msg ){
display( msg != null ? msg : "Done." );
addCommand( okCommand );
setCommandListener( SampleClient.this );
}
// Callback for making the HTTP connection.
public void prepareRequest(
String originalURL, HttpConnection conn )
throws IOException
{
conn.setRequestMethod(
HttpConnection.POST );
conn.setRequestProperty(
"User-Agent",
"Profile/MIDP-1.0 Configuration/CLDC-1.0" );
conn.setRequestProperty(
"Content-Language", "en-US" );
conn.setRequestProperty(
"Accept", "application/octet-stream" );
conn.setRequestProperty(
"Connection", "close" );
conn.setRequestProperty(
"Content-Length",
Integer.toString( data.length ) );
OutputStream os = conn.openOutputStream();
os.write( data );
os.close();
}
// Do the connection on a separate thread to
// keep the UI responsive...
public void run(){
HttpConnection conn = null;
display(
"Obtaining HttpConnection object..." );
try {
conn = HttpConnectionHelper.connect(
url, this );
display(
"Connecting to the server..." );
int rc = conn.getResponseCode();
if( rc == HttpConnection.HTTP_OK ){
StringBuffer text =
new StringBuffer();
// Here's where you read the data.
// This case expects an integer
// followed by zero or more
// strings.
try {
DataInputStream din =
new DataInputStream(
conn.openInputStream() );
int n = din.readInt();
while( n-- > 0 ){
text.append(
din.readUTF() );
text.append( '\n' );
}
}
catch( IOException e ){
}
done(
"Response is:\n" +
text.toString() );
} else {
done(
"Unexpected return code: " + rc );
}
}
catch( IOException e ){
done( "Exception " + e +
" trying to connect." );
}
}
// Starts the upload in the background...
void start(){
display( "Starting..." );
Thread t = new Thread( this );
try {
t.start();
}
catch( Exception e ){
done( "Exception " + e +
" trying to start thread." );
}
}
private StringItem message;
private byte[] data;
}
}
Notice how a separate thread is used to do the actual HTTP
communication -- you should always do this to keep the user
interface active and responsive.
. . . . . . . . . . . . . . . . . . . . . . .
- NOTE
Sun respects your online time and privacy. The Java Developer
Connection mailing lists are used for internal Sun
Microsystems(tm) purposes only. You have received this email
because you elected to subscribe. To unsubscribe, go to the
Subscriptions page (http://developer.java.sun.com/subscription/),
uncheck the appropriate checkbox, and click the Update button.
As of May 22, 2001, Sun Microsystems updated its Privacy Policy
(http://sun.com/privacy) to give you a better understanding of
Sun's Privacy Policy and Practice. If you have any questions,
contact privacy@sun.com.
- SUBSCRIBE
To subscribe to a JDC newsletter mailing list, go to the
Subscriptions page (http://developer.java.sun.com/subscription/),
choose the newsletters you want to subscribe to, and click Update.
- FEEDBACK
Comments? Send your feedback on the J2ME Tech Tips to:
jdc-webmaster@sun.com
- ARCHIVES
You'll find the J2ME Tech Tips archives at:
http://java.sun.com/jdc/J2METechTips/index.html
- COPYRIGHT
Copyright 2001 Sun Microsystems, Inc. All rights reserved.
901 San Antonio Road, Palo Alto, California 94303 USA.
This document is protected by copyright. For more information,
see:
http://java.sun.com/jdc/copyright.html
- LINKS TO NON-SUN SITES
The J2ME Tech Tips may provide, or third parties may provide,
links to other Internet sites or resources. Because Sun has no
control over such sites and resources, You acknowledge and
agree that Sun is not responsible for the availability of such
external sites or resources, and does not endorse and is not
responsible or liable for any Content, advertising, products,
or other materials on or available from such sites or resources.
Sun will not be responsible or liable, directly or indirectly,
for any damage or loss caused or alleged to be caused by or in
connection with use of or reliance on any such Content, goods or
services available on or through any such site or resource.
J2ME Tech Tips
August 20, 2001
Sun, Sun Microsystems, Java, Java Developer Connection, and
J2ME, JavaServer Pages, and JSP are trademarks or registered
trademarks of Sun Microsystems, Inc. in the United States and
other countries.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -