Network connection is often used to send data in mobile phone development. Like web, requests in mobile phone can be divided into GET requests and POST requests.
The following is an HttpProcess class that provides the way POST and GET requests are made.
package com.thinkrace.UCHome.network; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; /** * * @author Administrator */ public class HttpProcess { /** * HTTP GET Request mode * This method reads the returned xml one character at a time. * @param url * @return */ public static String HttpGET(String url) { String content = null; try { //Open Network Connection HttpConnection hc = (HttpConnection) Connector.open(url); hc.setRequestMethod(HttpConnection.GET); InputStreamReader isr = new InputStreamReader(hc.openInputStream(), "UTF-8"); int ch = 0; StringBuffer buf = new StringBuffer(); while ((ch = isr.read()) != -1) { buf.append((char) ch); } //Closing flow isr.close(); hc.close(); } catch (IOException ex) { System.out.println("HttpGET Method abnormality"); ex.printStackTrace(); } return content; } /** * GET requests that allocate fixed memory always display only 5k regardless of the size of the xml returned * The excess will be truncated and the rest will be filled with blanks. * @param url * @return */ public static String HttpGETByAssignMemory(String url) { String content = null; try { HttpConnection hc = (HttpConnection) Connector.open(url); hc.setRequestMethod(HttpConnection.GET); DataInputStream dis = new DataInputStream(hc.openDataInputStream()); //Allocate 5K memory byte[] data = new byte[1024 * 5]; dis.read(data); content = new String(data, "UTF-8"); } catch (IOException ex) { System.out.println("HttpGETByAllocateMemory Method abnormality"); ex.printStackTrace(); } return content; } public static String HttpPOST(String url, String argument) { String xml = null; try { HttpConnection hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE); hc.setRequestMethod(HttpConnection.POST); //Set POST header information, User Agent (Setting Agent), Content-Language (Language), Content-Type (Type), Content-Length(POST Length) hc.setRequestProperty("User-Agent", "Profile/MIDP-2.0 Configuration/CLDC-1.1"); hc.setRequestProperty("Content-Language", "en-US"); hc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); byte[] postData = argument.getBytes("UTF-8"); hc.setRequestProperty("Content-Length", Integer.toString(postData != null ? postData.length : 0)); OutputStream out = hc.openOutputStream(); out.write(postData); InputStream in = hc.openInputStream(); DataInputStream dis = new DataInputStream(in); int ch = 0; StringBuffer buf = new StringBuffer(); while((ch = dis.read()) != -1){ buf.append((char)ch); } xml = buf.toString(); } catch (IOException ex) { System.out.println("HttpPOST Method abnormality"); ex.printStackTrace(); } return xml; } /** * String Convert to byte array * @param str * @return */ public static byte[] StringtoBytes(String str) { byte[] data = null; try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeUTF(str); data = baos.toByteArray(); baos.close(); dos.close(); } catch (Exception ex) { System.out.println("StringtoBytes Method abnormality"); ex.printStackTrace(); } return data; } /** * byte[]Array to String * @param data * @return */ public static String BytesToString(byte[] data) { ByteArrayInputStream bais = new ByteArrayInputStream(data); DataInputStream dis = new DataInputStream(bais); String str = null; try { str = dis.readUTF(); bais.close(); dis.close(); } catch (Exception ex) { System.out.println("BytesToString Method abnormality"); ex.printStackTrace(); } return str; } }
Download a small picture as an example, a simpler HTTP connection demo.
It supports two different access modes of CMNET and CMWAP, and filters mobile tariff pages under CMWAP access mode.
It passed the test on 6120c.
import java.io.IOException; import java.io.InputStream; import javax.microedition.io.Connector; import javax.microedition.io.HttpConnection; import javax.microedition.lcdui.Command; import javax.microedition.lcdui.CommandListener; import javax.microedition.lcdui.Display; import javax.microedition.lcdui.Displayable; import javax.microedition.lcdui.Form; import javax.microedition.lcdui.Image; import javax.microedition.lcdui.StringItem; import javax.microedition.midlet.MIDlet; /** * HttpDemo * * @author kf156(Asia and Japan) * */ public class HttpTest extends MIDlet implements CommandListener, Runnable { public static final byte WAIT = 0;// wait for public static final byte CONNECT = 1;// In connection public static final byte SUCCESS = 2;// Success public static final byte FAIL = 3;// fail int state;// current state Display display = Display.getDisplay(this); Form form = new Form("HttpTest"); boolean cmnet = true;// Is the access point cmnet or cmwap StringBuffer sb = new StringBuffer("The current access mode is:CMNET\n"); StringItem si = new StringItem(null, sb.toString()); Command connect = new Command("networking", Command.OK, 1); Command change = new Command("Changing Access Point Mode", Command.OK, 2); Command exit = new Command("Sign out", Command.EXIT, 1); HttpConnection http; String host = "wiki.huihoo.com"; String path = "/images/9/9c/Java.gif"; public HttpTest() { state = WAIT;// Waiting state form.append(si); form.addCommand(connect); form.addCommand(change); form.addCommand(exit); form.setCommandListener(this); } protected void destroyApp(boolean b) { } protected void pauseApp() { } protected void startApp() { display.setCurrent(form); } public void commandAction(Command c, Displayable d) { if (c == change) {// Changing Access Points if (isConnect()) return; cmnet = !cmnet; form.deleteAll(); sb.delete(0, sb.length()); addStr("The current access mode is:" + (cmnet ? "CMNET" : "CMWAP")); form.append(si); } else if (c == connect) {// networking if (isConnect()) return; new Thread(this).start(); } else if (c == exit) {// Sign out destroyApp(true); notifyDestroyed(); } } public void run() { form.deleteAll(); sb.delete(0, sb.length()); addStr("The current access mode is:" + (cmnet ? "CMNET" : "CMWAP")); form.append(si); state = CONNECT; addStr("Network Connection..."); InputStream is = null; try { String url = null; url = cmnet ? ("http://" + host + path) : ("http://10.0.0.172:80" + path); http = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true); if (!cmnet) http.setRequestProperty("X-Online-Host", host); http.setRequestMethod(HttpConnection.GET); String contentType = http.getHeaderField("Content-Type"); System.out.println(contentType); addStr(contentType); if (contentType != null && contentType.indexOf("text/vnd.wap.wml") != -1) {// Filtering Mobile Fee Page addStr("Mobile tariff page, filtering!"); http.close(); http = null; http = (HttpConnection) Connector.open(url, Connector.READ_WRITE, true); if (!cmnet) http.setRequestProperty("X-Online-Host", host); http.setRequestMethod(HttpConnection.GET); contentType = http.getHeaderField("Content-Type"); } addStr("Content-Type=" + contentType); int code = http.getResponseCode(); addStr("HTTP Code :" + code); if (code == 200) { addStr("Network Connection Successful, Receiving Data..."); is = http.openInputStream(); Image image = Image.createImage(is); addStr("After receiving the data, display the pictures"); form.append(image); // Ordinary byte data reception // byte[] b = new byte[1024]; // int len = 0; // ByteArrayOutputStream baos = new ByteArrayOutputStream(); // DataOutputStream dos = new DataOutputStream(baos); // while ((len = is.read(b)) != -1) { // dos.write(b, 0, len); // } // dos.close(); // dos = null; // is.close(); // is = null; state = SUCCESS; return; } else { addStr("Failed to access the page"); } } catch (IOException e) { addStr("Network anomalies:" + e.toString()); e.printStackTrace(); } catch (Exception e) { addStr("Abnormal:" + e.toString()); e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } is = null; } if (http != null) try { http.close(); } catch (IOException e) { e.printStackTrace(); } http = null; } state = FAIL; } /** * Determine whether the connection is in progress * * @return */ private boolean isConnect() { if (state == CONNECT) { addStr("Please wait while the network connection is in progress...."); return true; } return false; } /** * Add text * * @param str * Text to add */ private void addStr(String str) { sb.append(str + "\n"); si.setText(sb.toString()); } }
Reprinted at: https://www.cnblogs.com/psunny/archive/2009/12/06/1617875.html