|
How to implement networking on mobile devices |
|
|
javax.microedition.io package includes networking support based
on Generic Connection Framework for MIDP profile.
Illustration below use HTTP protocol to read data from URL.
//Reads HTTP header and data
import java.io.*;
import javax.microedition.midlet.*;
import javax.microedition.io.*;
import javax.microedition.lcdui.*;
public class httpMIDLET extends MIDlet
{
private Display display;
private String url = "http://server/hello.txt";
public httpMIDLET()
{
display = Display.getDisplay(this);
}
public void startApp()
{
getData(url);
}
private void getData(String url) throws IOException
{
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
TextBox t = null;
try
{
long len = 0 ;
int ch = 0;
c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len =c.getLength();
if( len != -1)
{
// Read exactly Content-Length bytes
for(int i =0 ; i < len ; i++ )
{
if((ch = is.read()) != -1)
{
b.append((char) ch);
}
}
}
else
{
//Read until the connection is closed.
while ((ch = is.read()) != -1)
{
len = is.available() ;
b.append((char)ch);
}
}
t = new TextBox("Http Data",b.toString(), 1024, 0);
}
finally
{
is.close();
c.close();
}
display.setCurrent(t);
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) { }
}
|
Below method post a request with some headers and content to server.
public void postHttpdata(Sring url) throws IOException
{
HttpConnection c = 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","7 Sep 2005 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("How are you\n".getBytes());
os.flush();
}
finally
{
os.close();
c.close();
}
}
|
Related Tips
|
Page 1 of 0 ( 0 comments )
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.