Java Tutorial/J2ME/HttpConnection
Содержание
An example MIDlet to fetch a page using an HttpConnection
/* License
*
* Copyright 1994-2004 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistribution of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MICROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
/**
* An example MIDlet to fetch a page using an HttpConnection.
*/
public class J2MESecondExample extends MIDlet {
private Display display;
private String url = "http://www.y.ru/hello.txt";
public J2MESecondExample() {
display = Display.getDisplay(this);
}
/**
* This will be invoked when we activate the MIDlet.
*/
public void startApp() {
// Use the specified URL is overriden in the descriptor
try {
downloadPage(url);
} catch (IOException e) {
// handle the exception
}
}
private void downloadPage(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 till the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available();
b.append((char) ch);
}
}
t = new TextBox("hello again....", b.toString(), 1024, 0);
} finally {
is.close();
c.close();
}
display.setCurrent(t);
}
/**
* Pause, discontinue....
*/
public void pauseApp() {
}
/**
* Destroy must cleanup everything.
*/
public void destroyApp(boolean unconditional) {
}
}
An example MIDlet to invoke a CGI script (POST method is used).
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.TextBox;
import javax.microedition.midlet.MIDlet;
public class InvokeCgiMidlet2 extends MIDlet {
private Display display;
String url = "http://www.g.ru/get.cgi";
public InvokeCgiMidlet2() {
display = Display.getDisplay(this);
}
public void startApp() {
try {
getGrade(url);
} catch (IOException e) {
e.printStackTrace();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void getGrade(String url) throws IOException {
HttpConnection c = null;
InputStream is = null;
OutputStream os = null;
StringBuffer b = new StringBuffer();
TextBox t = null;
try {
c = (HttpConnection) Connector.open(url);
c.setRequestMethod(HttpConnection.POST);
c.setRequestProperty("CONTENT-TYPE", "application/x-www-form-urlencoded");
c.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Confirguration/CLDC-1.0");
c.setRequestProperty("Content-Language", "en-CA");
os = c.openOutputStream();
String str = "name=1";
byte postmsg[] = str.getBytes();
for (int i = 0; i < postmsg.length; i++) {
os.write(postmsg[i]);
}
os.flush();
is = c.openDataInputStream();
int ch;
while ((ch = is.read()) != -1) {
b.append((char) ch);
}
t = new TextBox("Final Grades", b.toString(), 1024, 0);
}
display.setCurrent(t);
}
}
Load Image with HttpConnection
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.StringItem;
import javax.microedition.midlet.MIDlet;
public class ImageLoaderMIDlet extends MIDlet {
private Item mItem;
public void startApp() {
final Display display = Display.getDisplay(this);
Form mainForm = new Form("Loading...");
display.setCurrent(mainForm);
final Form imageForm = new Form("Image");
imageForm.addCommand(new Command("Exit", Command.EXIT, 0));
imageForm.setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable s) {
notifyDestroyed();
}
});
Thread t = new Thread() {
public void run() {
try {
String URL = "http://localhost/Duke.png";
Image image = loadImage(URL);
mItem = new ImageItem(null, image, 0, null);
} catch (IOException ioe) {
mItem = new StringItem(null, ioe.toString());
}
imageForm.append(mItem);
display.setCurrent(imageForm);
}
};
t.start();
}
public Image loadImage(String url) throws IOException {
HttpConnection hpc = null;
DataInputStream dis = null;
try {
hpc = (HttpConnection) Connector.open(url);
int length = (int) hpc.getLength();
byte[] data = new byte[length];
dis = new DataInputStream(hpc.openInputStream());
dis.readFully(data);
return Image.createImage(data, 0, data.length);
} finally {
if (hpc != null)
hpc.close();
if (dis != null)
dis.close();
}
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
}
Response Header
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.DateField;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
public class ResponseHeaderMIDlet extends MIDlet implements CommandListener {
private Command exitCommand = new Command("Exit", Command.EXIT, 1);
private Command sendCommand = new Command("Send", Command.OK, 1);
private Command backCommand = new Command("Upload", Command.OK, 1);
private Display display;
private String defaultURL = "http://localhost/";
private Form mainForm, resultForm;
private TextField URL;
private DateField DateField1 = new DateField("Date", DateField.DATE_TIME);
private DateField DateField2 = new DateField("Expiration", DateField.DATE_TIME);
private DateField DateField3 = new DateField("Last Modified", DateField.DATE_TIME);
private StringItem resultItem;
public ResponseHeaderMIDlet() {
display = Display.getDisplay(this);
}
public void startApp() {
URL = new TextField(null, defaultURL, 250, TextField.URL);
mainForm = new Form("Test");
mainForm.append(URL);
mainForm.addCommand(sendCommand);
mainForm.addCommand(exitCommand);
mainForm.setCommandListener(this);
display.setCurrent(mainForm);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
public void commandAction(Command c, Displayable s) {
if (c == sendCommand) {
String result = "";
resultItem = new StringItem(null, result);
resultForm = new Form("");
String URLString = URL.getString();
try {
result = requestUsingGET(URLString);
} catch (IOException e) {
result = "Falied";
}
resultItem.setText(result);
resultForm.append(resultItem);
resultForm.append(DateField1);
resultForm.append(DateField2);
resultForm.append(DateField3);
resultForm.addCommand(backCommand);
resultForm.setCommandListener(this);
display.setCurrent(resultForm);
} else if (c == backCommand) {
URL.setString(defaultURL);
display.setCurrent(mainForm);
} else {
destroyApp(false);
notifyDestroyed();
}
}
private String requestUsingGET(String URLString) throws IOException {
HttpConnection hpc = null;
String content = "";
try {
hpc = (HttpConnection) Connector.open(URLString);
int status = hpc.getResponseCode();
if (status != HttpConnection.HTTP_OK)
content = "Falied";
else {
DateField1.setDate(new java.util.Date(hpc.getDate()));
DateField2.setDate(new java.util.Date(hpc.getExpiration()));
DateField3.setDate(new java.util.Date(hpc.getLastModified()));
content += "Content Type: " + hpc.getType() + "\n";
content += "Content Length: " + hpc.getLength() + "\n";
content += "Contnet Encoding: " + hpc.getEncoding() + "\n";
}
if (hpc != null)
hpc.close();
} catch (IOException e2) {
}
return content;
}
}
Use HttpConnection
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.rumand;
import javax.microedition.lcdui.rumandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class HttpMIDlet extends MIDlet implements CommandListener, Runnable {
private Display display;
private Form addressForm = new Form("HTTP Client");
private Form connectForm = new Form("Connecting");
private Form displayForm = new Form("Server Reply");
private TextField serverURL = new TextField("URL:", "", 256, TextField.ANY);
private StringItem messageLabel = new StringItem(null, "Connecting...\nPlease wait.");
private Command okCommand = new Command("OK", Command.OK, 0);
private Command exitCommand = new Command("Exit", Command.EXIT, 0);
private Command backCommand = new Command("Back", Command.BACK, 0);
protected void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
addressForm.append(serverURL);
addressForm.addCommand(okCommand);
addressForm.addCommand(exitCommand);
addressForm.setCommandListener(this);
connectForm.append(messageLabel);
connectForm.addCommand(backCommand);
connectForm.setCommandListener(this);
displayForm.append(messageLabel);
displayForm.addCommand(backCommand);
displayForm.setCommandListener(this);
display.setCurrent(addressForm);
}
protected void pauseApp() {
}
protected void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
}
public void commandAction(Command cmd, Displayable d) {
if (cmd == okCommand) {
Thread t = new Thread(this);
t.start();
display.setCurrent(connectForm);
} else if (cmd == backCommand) {
display.setCurrent(addressForm);
} else if (cmd == exitCommand) {
try {
destroyApp(true);
} catch (MIDletStateChangeException ex) {
}
notifyDestroyed();
}
}
public void run() {
InputStream is = null;
HttpConnection conn = null;
try {
String url = serverURL.getString();
if (!url.startsWith("http://") && !url.startsWith("https://")) {
url = "http://" + url;
}
conn = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
if (conn.getResponseCode() == HttpConnection.HTTP_OK) {
is = conn.openInputStream();
final int MAX_LENGTH = 128;
byte[] buf = new byte[MAX_LENGTH];
int total = 0;
while (total < MAX_LENGTH) {
int count = is.read(buf, total, MAX_LENGTH - total);
if (count < 0) {
break;
}
total += count;
}
is.close();
String reply = new String(buf, 0, total);
messageLabel.setText(reply);
} else {
messageLabel.setText("Failed: error " + conn.getResponseCode() + "\n"+ conn.getResponseMessage());
}
conn.close();
display.setCurrent(displayForm);
} catch (IOException ex) {
System.out.println(ex);
ex.printStackTrace();
Alert alert = new Alert("I/O Error","An error occurred while communicating with the server.", null,AlertType.ERROR);
alert.setTimeout(Alert.FOREVER);
display.setCurrent(alert, addressForm);
return;
}
}
}