开发J2ME联网应用程序(4)

分类: J2ME   出处:iocblog整理  更新时间:2008-08-12   添加到收藏  


import java.io.*;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;


public class HttpCommHandler
{
   private String URL;

   public HttpCommHandler(String URL)
   {
       this.URL = URL;
   }

   public String sendMessage(String message) throws IOException
   {
       HttpConnection httpConn;
       DataInputStream input;
       DataOutputStream output;
       String result;
       try
       {
           httpConn = open();
           output = this.openDataOutputStream(httpConn);
           output.writeUTF(message);
           output.close();
           input = this.openDataInputStream(httpConn);
           result = input.readUTF();
           closeConnection(httpConn,input,output);
           return result;

       }

       finally 
       {

       }

   }

   public HttpConnection open() throws IOException
   {
       try
       {
           HttpConnection connection = (HttpConnection) Connector.open(URL);

           connection.setRequestProperty("User-Agent", System
                   .getProperty("microedition.profiles"));
           connection.setRequestProperty("Content-Type",
                   "application/octet-stream");
           connection.setRequestMethod(HttpConnection.POST);

           return connection;
       } catch (IOException ioe)
       {

           throw ioe;
       }

   }

   private DataInputStream openDataInputStream(HttpConnection conn)
           throws IOException

   {
       int code = conn.getResponseCode();
       if (code == HttpConnection.HTTP_OK)
       {
           return conn.openDataInputStream();
       } else
       {
           throw new IOException();
       }
   }

   private DataOutputStream openDataOutputStream(HttpConnection conn)
           throws IOException
   {
       return conn.openDataOutputStream();
   }

   private void closeConnection(HttpConnection conn, DataInputStream dis,
           DataOutputStream dos)
   {
       if(conn!= null)
       {
           try
           {
               conn.close();
           }
           catch(IOException e)
           {}
       }
       
       if(dis!=null)
       {
           try
           {
               dis.close();
           }
           catch(IOException e)
           {}
       }
       
       if(dos!=null)
       {
           try
           {
               dos.close();
           }
           catch(IOException e)
           {}
       }
       
   }

}

上一页 [1] [2] [3] [4] [5] 下一页


Tag: 联网开发