在无线J2ME设备上实现超文本传输协议
2006-8-7 14:33:00 文/javajia 出处:javajia
// 从服务器上取回响应
int ch;
while ( ( ch = dis.read() ) != -1 ) {
responseMessage.append( (char) ch );
}//结束while ( ( ch = dis.read() ) != -1 )
}
catch( Exception e )
{
e.printStackTrace();
responseMessage.append( "ERROR" );
} finally {
try {
if ( hcon != null ) hcon.close();
if ( dis != null ) dis.close();
} catch ( IOException ioe ) {
ioe.printStackTrace();
}//结束try/catch
}//结束try/catch/finally
return responseMessage.toString();
}//结束sendHttpGet( String )
private String sendHttpPost( String url )
{
HttpConnection hcon = null;
DataInputStream dis = null;
DataOutputStream dos = null;
StringBuffer responseMessage = new StringBuffer();
// 请求体
String requeststring = "This is a POST.";
try {
// 使用读写权限的 HttpConnection
hcon = ( HttpConnection )Connector.open( url, Connector.READ_WRITE );
//设置请求方法为POST
hcon.setRequestMethod( HttpConnection.POST );
// 取得发送请求字符串的DataOutputStream
dos = hcon.openDataOutputStream();
byte[] request_body = requeststring.getBytes();
// 发送请求字符串到服务器
for( int i = 0; i < request_body.length; i++ ) {
dos.writeByte( request_body[i] );
}//结束 for( int i = 0; i < request_body.length; i++ )
// 取得做为接收服务器响应的DataInputStream
dis = new DataInputStream( hcon.openInputStream() );
// 从服务器上取回响应
int ch;
while( ( ch = dis.read() ) != -1 ) {
responseMessage.append( (char)ch );
}//结束while( ( ch = dis.read() ) != -1 ) {
}
catch( Exception e )
{
e.printStackTrace();
responseMessage.append( "ERROR" );
}
finally {
// 释放输入输出流和HTTP连接
try {
if( hcon != null ) hcon.close();
if( dis != null ) dis.close();
if( dos != null ) dos.close();
} catch ( IOException ioe ) {
ioe.printStackTrace();
}//结束try/catch
}//结束try/catch/finally
return responseMessage.toString();
}//结束sendHttpPost( String )
public void pauseApp() {
}//结束pauseApp()
public void destroyApp( boolean unconditional ) {
myDisplay = null;
requestScreen = null;
requestField = null;
resultScreen = null;
resultField = null;
}//结束 destroyApp( boolean )
}//结束HttpMidlet