两种HTTP连接方式POST&GET的比较(2)
String encodedData = encode( rawData ); // user-supplied
try {
   conn = (HttpConnection) Connector.open( url );
   conn.setRequestMethod( HttpConnection.POST );
   conn.setRequestProperty( "User-Agent", agent );
   conn.setRequestProperty( "Content-Type", type );
   conn.setRequestProperty( "Content-Length", 
       encodedData.length() );
   OutputStream os = conn.openOutputStream();
   os.write( encodedData.getBytes() );
    
       int rc = conn.getResponseCode();
   ... // process it
}
catch( IOException e ){
   // handle the error here
}
从上面的代码我们可以看出,如果使用POST方法,通常我们应该设置一些Headers,可以通过setRequestProperty()方法完成,其 中 Content-Type和Content-Length是非常重要的,在MIDP中经常使用的Content-Type是 application/octet-stream和application/x-www-form-urlencoded,前者用于发送二进制数据,后 者可以用于发送属性-数值对。我们最好在联网的时候设置这两个Header,因为这样服务器将很容易的知道将有什么类型的数据,多少数据发送过来。
    在使用POST方法发送数据的时候,通常要涉及到io的知识,我们需要打开流,发送数据,关闭流。例如
    void postViaHttpConnection(String url) throws IOException {
        HttpConnection c = null;
        InputStream is = null;
        OutputStream os = null;
        try {
            c = (HttpConnection)Connector.open(url);
            // Set the request method and headers
            c.setRequestMethod(HttpConnection.POST);
            c.setRequestProperty("If-Modified-Since",
                "29 Oct 1999 19:43:31 GMT");
            c.setRequestProperty("User-Agent",
                "Profile/MIDP-1.0 Configuration/CLDC-1.0");
            c.setRequestProperty("Content-Language", "en-US");
            // Getting the output stream may flush the headers
            os = c.openOutputStream();
            os.write("LIST games\n".getBytes());
            os.flush();                // Optional, openInputStream will flush
相关新闻>>
- 发表评论
- 
				
- 最新评论 进入详细评论页>>






