This paper describes the development of the main network connection method in J2me, and introduces two methods of using HTTP and socket in detail respectively.
Httpconnection
Let's first look at a simple example:
Java packages that are used primarily:
javax.microedition.io.*;
public string Requestget (String urlstring,string URL) throws ioexception{
//=============================================================
//URLString is an HTTP address, and the URL is the following parameter
//The example here is to send the username and password to the server side for user authentication
//such as String urlstring = "http://192.168.0.1:8080/login.jsp";
//String URL = "? Name= "+this.txtname+" &pass= "+this.txtpass
//=============================================================
httpconnection HPC = null;
DataInputStream dis = null;
Boolean newline = false;
String content = "";
try{
//===========================================================
//Establish a connection
//===========================================================
HPC = (httpconnection) connector.open (Urlstring+url);
Hpc.setrequestmethod (Httpconnection.get);
dis = new DataInputStream (Hpc.openinputstream ());
int character;
//===========================================================
//Read the returned HTTP content
//===========================================================
while (character = Dis.read ())!=-1) {
if ((char) character = = ' \ ') {
newline = true;
continue;
}
else{
if ((char) character = = ' n ' && newline) {
content + = "\ n";
newline = false;
}
else if (newline) {
Content + = "\" + (char) character;
newline = false;
}
else{
content + = (char) character;
newline = false;
}
}
}
}
catch (IOException e) {
System.out.print ("ERROR:" +e);
}
finally{
if (HPC!= null) {
Hpc.close ();
HPC = null;
}
if (dis!= null) {
Dis.close ();
}
}
//===============================================================
//Because content may have Chinese, it is necessary to convert the content to a character set after receiving the information
//===============================================================
content = (unicodeTogb2312 (content)). Trim ();
return content;
}
public static string unicodeTogb2312 (string s) {
if (s==null) {return "";}
if (S.equals ("")) {return s;}
try{
return new String (S.getbytes ("Iso8859_1"), "gb2312");
}
catch (Exception uee) {
return s;
}
}
The above is a simple HTTP connection and get response information from the server example, should be very simple. The client is the above, server-side as long as the configuration of IIS, add a Web page to the client's request to respond to the line, in fact, with the general requirements of the Web page is not much different, very simple!!
The above socket client connection program should be completed, the following is to build a server-side connection to the client to respond. To establish a server-side program, you only need the following code: