开发J2ME联网应用程序(4)
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)
{}
}
}
}
Tag: 联网开发