歡迎您光臨本站 註冊首頁

在無線J2ME設備上實現http傳輸(2)

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

如何發送一個HTTP POST 請求
你可以想象,發送一個HTTP POST 請求的處理過程其實與發送一個GET 請求
非常地類似.我們將修改一個現有命令,添加少量的新的命令,並添加一個來自
通用連接框架的附加的對象和一個附加的StringBuffer對象把POST請求體重的內
容發送到伺服器中.剩下的命令將保持不變.
複製我們剛才創建的sendHttpGet ()方法,把它粘貼進同一個類文件,改
名為sendHttpPost().現在,我們將修改這個新方法來發送一個HTTP POST 請
求到伺服器.在方法的頂部添加兩個新的變數說明.聲明一個類型為DataOutputStream
的變數和另一個String類型的變數.我們將使用DataOutputStream對象把存在於
字元串變數中的POST請求體發送到伺服器中.
DataOutputStream dos = null ;String requestBody = null ;
修改connector.open()命令包含另一個參數,指出連接將允許客戶端可以
通過連接在伺服器上讀和寫.
hcon =( HttpConnection ) Connector.open ( url,Connector.READ_WRITE )

設置HttpConnection對象使用的請求方法為POST(默認的方法是GET ).
hcon.setRequestMethod ( HttpConnection.POST);
得到一個用於現有的HTTP連接的DataOutputStream對象.
dos = hc.openDataOutputStream ();
聲明一個位元組數組並通過檢索一個來自requestBody 字元串的位元組數組初始
化.然後把DataOutputStream的緩衝寫入位元組數組內.
byte[] byteRequest = requestBody.getBytes ();
for ( int i = 0;i < byteRequest.length; i ){
dos.writeByte (byteRequest[i]);
}// 結束for ( int i = 0; i <byteRequest.length; i )
dos.flush (); // 包含本句,在某些設被上將可能會產生不可預期的結

調用flush ()方法的意圖是發送已經寫入的數據到DataOutputStream的服
務器的緩衝區中.在某些電話上,這個操作工作正常,在其他的電話上,它導致
HTTP請求的Transfer - Encoding 被設置為「chunked 」,有一些隨機字元被放
到請求本身的前面和後面.那又怎樣處理這個問題呢?這個方法調用實際上是根
本不需要的.
在接下來的一行中,伺服器連接打開(通過openInputStream ()),將自
動輸入緩衝區.因此,你最好不要調用緩衝區的flush ()方法.這個方法其餘
的部分保持不變,除了DataOutputStream對象必須在finally{} 語句塊中關閉.
} finally {
if( hc != null) hc.close ();
if ( dis!= null)
dis.close ();
if ( dos!= null) dis.close();
}//結束 try/finally
這就是所有的程序代碼!並請參見本文後附帶的程序代碼.


隨著可以使用國際互聯網路和支持網路的無線設備日益的增多普及,Java和
J2ME的重要性也在不斷的變大.HTTP協議是當前僅有的,被所有的遵從MIDP
規範的設備支持的網路協議,它也是用於開發無線網路應用程序的最好的候選者.
在本文中,我們探究了無線網路編程的基本結構和幾個核心問題,我們看了
如何調用兩個最常用的HTTP請求方法:GET 和POST.J2ME 仍然在它的發展初期,
並且無線設備也即將得到大面積的普及.,所有有志投身於無線網路編程中
的開發者們將得到大展拳腳的好機會.

附錄:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.* ;
import java.io.* ;
public class HttpMidlet extends MIDlet implements CommandListener {
//使用默認的URL.用戶可以從圖形用戶介面改變這個值
private static String defaultURL =
"http://localhost:8080/test/servlet/EchoServlet";
//主MIDP顯示
private Display myDisplay= null;
//輸入URL 的圖形用戶介面組件
private Form requestScreen ;
private TextField requestField;
//用於提交請求的圖形用戶介面組件
private List list;
private String[] menuItems ;
//用於顯示伺服器響應的圖形用戶介面組件
private Form resultScreen;
private StringItem resultField ;
//用於requestScreen 的"send"按鈕
Command sendCommand;
// 用於requestScreen的"exit"按鈕
Command exitCommand;
// 用於requestScreen 的"back"按鈕
Command backCommand ;
public HttpMidlet (){
//初始化圖形用戶介面組件
myDisplay= Display.getDisplay( this );
sendCommand
exitCommand = new Command( "EXIT" , Command.OK , 1);
backCommand = new Command( "BACK" ,Command.OK, 1);
//顯示請求的URL
requestScreen = new Form( "Type in a URL :" );
requestField = new TextField ( null , defaultURL , 100,
TextField.URL );
requestScreen.append ( requestField );
requestScreen.addCommand( sendCommand);
requestScreen.addCommand ( exitCommand);
requestScreen.setCommandListener( this );
//選擇想要的HTTP請求方法
menuItems = new String[] {"GET Request","POST Request"} ;
list = new List( "Select an HTTP method :" ,
List.IMPLICIT,menuItems , null );
list.setCommandListener( this );
//先是從伺服器上收到的信息
resultScreen = new Form( "Server Response :" );
resultScreen.addCommand( backCommand);


resultScreen.setCommandListener( this );
}// 結束HttpMidlet()
public void startApp() {
myDisplay.setCurrent ( requestScreen );
}//結束 startApp ()
public void commandAction ( Command com,
Displayable disp) {
// 當用戶點擊"send"按鈕
if ( com == sendCommand ){
myDisplay.setCurrent( list );
} else if( com == backCommand ){
requestField.setString( defaultURL );
myDisplay.setCurrent ( requestScreen);
} else if( com == exitCommand ) {
destroyApp ( true );
notifyDestroyed() ;
}//結束 if ( com == sendCommand )
if( disp == list && com ==List.SELECT_COMMAND ){String result;if( list.getSelectedIndex() == 0 ) // 發送一個
GET 請求到伺服器 result = sendHttpGet ( requestField.getString ())
; else //發送一個 POST 請求到伺服器
result = sendHttpPost( requestField.getString());
resultField = new StringItem( null , result );
resultScreen.append( resultField);
myDisplay.setCurrent ( resultScreen );
}//結束if( dis == list && com == List.SELECT_COMMAND)
}//結束 commandAction(Command , Displayable)
private String sendHttpGet( String url )
{
HttpConnection hcon = null;
DataInputStream dis = null ;
StringBuffer responseMessage = new StringBuffer();
try {
//使用READ許可權的標準的 HttpConnection
hcon =( HttpConnection )Connector.open( url);
//從HttpConnection取得一個 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 {
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 { i
f ( 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


[火星人 ] 在無線J2ME設備上實現http傳輸(2)已經有289次圍觀

http://coctec.com/docs/java/show-post-60017.html