- package HttpConnection;
- import java.io.DataInputStream;
- import java.io.IOException;
- import javax.microedition.io.ConnectionNotFoundException;
- import javax.microedition.io.Connector;
- import javax.microedition.io.HttpConnection;
- /**********************************************************************
- *
- * @author
- *Description:发送请求消息,返回字符串数据
- ***********************************************************************/
- public class HttpStringThread implements Runnable{
- String host;
- String parameter;
- HttpConnection hc;
- DataInputStream dis;
- public String result;
- String canvas;
- String resURL;
- TaskInterface ti;
- public HttpStringThread(String resURL,TaskInterface ti){
- this.resURL = resURL;
- this.canvas=null;
- if(resURL.indexOf("/") == -1){
- host = resURL;
- parameter = "";
- }else{
- host = resURL.substring(0,resURL.indexOf("/"));
- parameter = resURL.substring(resURL.indexOf("/"));
- }
- this.ti=ti;
- }
- public HttpStringThread(String resURL){
- ti=null;
- this.resURL = resURL;
- this.canvas=null;
- if(resURL.indexOf("/") == -1){
- host = resURL;
- parameter = "";
- }else{
- host = resURL.substring(0,resURL.indexOf("/"));
- parameter = resURL.substring(resURL.indexOf("/"));
- }
- }
- public HttpStringThread(String resURL,TaskInterface ti,String canvas){
- this.resURL = resURL;
- this.canvas=canvas;
- if(resURL.indexOf("/") == -1){
- host = resURL;
- parameter = "";
- }else{
- host = resURL.substring(0,resURL.indexOf("/"));
- parameter = resURL.substring(resURL.indexOf("/"));
- }
- this.ti=ti;
- }
- public void run() {
- // TODO 自动生成方法存根
- try {
- /*
- hc = (HttpConnection)Connector.open("http://" + "10.0.0.172:80" //注,这里重点,代表某种机子通信需要代理
- + parameter,3,true); //服务地址,才能实现无线通信,
- hc.setRequestProperty("X-Online-Host",host);
- hc.setRequestProperty("Connection","close");
- */
- hc = (HttpConnection)Connector.open("http://"+resURL); //这种通信代表某和机子已经包含有代理服务地址
- hc.setRequestMethod(HttpConnection.GET); //设置
- dis = hc.openDataInputStream();
- int k;
- byte[] data = new byte[10240];
- int i = 0;
- while((k = dis.read()) != -1){
- data[i] = (byte)k;
- i++;
- }
- String s = new String(data,0,i);
- result=s;
- System.out.println("This is HttpStringThread");
- }catch(NullPointerException e){
- result="CommunicationError";
- }catch(ConnectionNotFoundException e){
- result="CommunicationError";
- }catch(IOException e){
- result="CommunicationError";
- }catch(Exception e){
- result="CommunicationError";
- }finally{
- System.out.println(result);
- try {
- hc.close();
- if(dis!=null){
- dis.close();
- }
- } catch (IOException e) {
- // TODO 自动生成 catch 块
- e.printStackTrace();
- }
- if(this.canvas!=null){
- ti.data(result, this.canvas);
- }else{
- ti.data(result);
- }
- }
- }
- }
J2ME 中的无线通信协议
最新推荐文章于 2025-07-23 15:24:15 发布