⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 connection.java

📁 j2me 用socket伪装http实现长连接。从而避免频繁的联网提示。支持cmwap。
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
package com.zxy.j2me.utils;

import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Vector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.SocketConnection;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.Connector;
import java.util.Hashtable;
import java.util.Enumeration;


/**
 * <p>Title: </p>
 *
 * <p>Description: </p>
 *
 * <p>Copyright: Copyright (c) 2006</p>
 *
 * <p>Company: </p>
 *
 * @author not attributable
 * @version 1.0
 */

public class Connection {
  public final static int METHODGET = 0;
  public final static int METHODPOST = 1;

  private final static int SLEEP_TIME = 100;

  String url;
  String uri;
  InputStream is = null;
  OutputStream os = null;
  final String shema = "http://";
  //用cnwap
  final String proxy = "10.0.0.172:80";
  final String endMark = "</rss>";
  final String CONTENT_LENGTH = "Content-Length";
  final String HTTP_STATUS = "HTTP/1.";

  String domain;
  public boolean reconnection;

  byte[] postBody;
  Hashtable headers = new Hashtable();
  int method = 0;
  //是否用cnwap
  boolean useProxy = false;
  //是否用socket
  boolean useSocket = true;
  //一个连接对象,可能是socket 也可能是http
  StreamConnection conn;
  byte[] buffer = new byte[1500];

  protected char iLineBuffer[];
  protected int iLineBufferLength;
  protected int iLineLength;
  protected int iResponseCode;
  protected long iLength = -1;
  protected final static int DEFAULT_LINE_BUFFER_SIZE = 128;
  protected final static int MINIMUM_STATUS_LINE_LENGTH;
  protected final static int VERSION_LENGTH;
  protected final static byte VERSION[] = {
                                          72, 84, 84, 80, 47, 49, 46, 49
  };
  protected Hashtable iReplyHeaders = new Hashtable();
  protected Vector iReplyHeaderKeys = new Vector();
  protected String iResponseMessage;
  static {
    VERSION_LENGTH = VERSION.length;
    MINIMUM_STATUS_LINE_LENGTH = VERSION_LENGTH + 5;
  }

  public void setUrl(String url, boolean useProxy) {
    this.headers.clear();
    this.url = url;
    String[] s = this.splitUrl(url);
    if (s[0].indexOf(":") == -1) {
      s[0] += ":80";
    }
    domain = s[0];
    uri = s[1];
    this.useProxy = useProxy;
    if (useProxy) {
      setHeader("X-Online-Host", domain);
    }
    setHeader("Host", domain);
    String platForm = System.getProperty("microedition.platform");
    if(platForm!=null)
      setHeader("User-Agent",platForm);
    else
      setHeader("User-Agent","MIDP 2.0");
  }

  public void setMethod(int method) {
    this.method = method;
  }

  public void setHeader(String header, String value) {
    this.headers.put(header, value);
  }


  private String[] splitUrl(String url) {
    String[] urls = new String[2];
    int shemaLen = shema.length();
    int posStart = url.toLowerCase().indexOf(shema);
    int posEnd;
    if (posStart == -1) {
      return null; //throw new Exception( "no http schema" );
    }
    posEnd = url.indexOf("/", shemaLen);
    if (posEnd == -1) {
      urls[0] = url.substring(shemaLen, url.length());
      urls[1] = "/";
    } else {
      urls[0] = url.substring(shemaLen, posEnd);
      urls[1] = url.substring(posEnd);
    }
    return urls;
  }

  private String genHeader() {
    StringBuffer header = new StringBuffer();
    if (method == METHODGET) {
      header.append("GET");
    }
    if (method == METHODPOST) {
      header.append("POST");
    }
    header.append(" " + this.uri);
    header.append(" HTTP/1.1\r\n");
    if (this.method == this.METHODPOST && postBody != null &&
        postBody.length > 0) {
      header.append(CONTENT_LENGTH + ": " + postBody.length + "\r\n");
    }
    Enumeration e = headers.keys();
    while (e.hasMoreElements()) {
      String h = (String) e.nextElement();
      header.append(h + ": " + (String) (headers.get(h)));
      header.append("\r\n");
    }
    header.append("\r\n");
    String ret = header.toString();
    header = null;
    return ret;
  }
  //进行联网
  public void connect() {
    this.useSocket = true;
    if (this.useSocket) {
      doConnect();
    }
  }

  public void close() {
    try {
      if (conn != null) {
        conn.close();
      }
      conn = null;
    } catch (IOException ex) {
    }
  }
  //首先是关闭流,然后调用联网函数
  private void doConnect() {
      //关闭打开的所有流
    try {
      if (is != null) {
        is.close();
      }
      is = null;
    } catch (IOException ex) {
    }
    try {
      if (os != null) {
        os.close();
      }
      os = null;
    } catch (IOException ex) {
    }
    try {
      if (conn != null) {
        conn.close();
      }
      conn = null;
    } catch (IOException ex) {
    }
    //全新的开始
    conn = requireConnection();
  }
  //请求连接,并返回一个连接好的对象。
  private StreamConnection requireConnection() {
    StreamConnection c = null;
    //是否穿越
    while (this.useSocket) {
      try {//是否代理cnwap
        if (this.useProxy) {
            //打开端口
          c = (SocketConnection) Connector.open("socket://" + proxy);
        } else {
          c = (SocketConnection) Connector.open("socket://" + domain);
        }
        if (c == null) {
          return null;
        }
        //设置连接属性
        ((SocketConnection) c).setSocketOption(SocketConnection.RCVBUF, 8192);
        //打开流
        is = c.openInputStream();
        os = c.openOutputStream();
        break;//出错之后 休息0.1秒 继续进行
      } catch (IOException ex) {
        try {
          Thread.sleep(SLEEP_TIME);
        } catch (InterruptedException e) {
        }
      } catch (SecurityException se) {
        this.useSocket = false;
        break;
      }
    }
    //用http去连接。
    while (!this.useSocket) {
      HttpConnection hc;
      try {
        if (this.useProxy) {
          c = (HttpConnection) Connector.open("http://" + proxy + uri);
        } else {
          c = (HttpConnection) Connector.open(url);
        }
        break;
      } catch (IOException ex) {
        try {
          Thread.sleep(SLEEP_TIME);
        } catch (InterruptedException e) {
        }
      }
    }
    return c;
  }

  public void send(byte[] body) {
    if (this.useSocket) {
      sendSocket(body);
    } else {
      sendHttp(body);
    }
  }

  private void sendHttp(byte[] body) {
    doConnect();
    HttpConnection hc = (HttpConnection) conn;
    while (true) {
      try {
        Enumeration e = headers.keys();
        hc.setRequestMethod(method == this.METHODGET ?
                            HttpConnection.GET :
                            HttpConnection.POST);
        if (this.method == this.METHODPOST) {
          hc.setRequestProperty(CONTENT_LENGTH,
                                Integer.toString(body.length));
        } while (e.hasMoreElements()) {
          String header = (String) e.nextElement();
          String value = (String) headers.get(header);
          hc.setRequestProperty(header, value);
        }
        if (this.method == this.METHODPOST) {
          os = hc.openOutputStream();
          os.write(body);
          //os.flush();
        }
        break;
      } catch (IOException ex) {
        long lstart = System.currentTimeMillis();
        this.connect();
        long lend = System.currentTimeMillis();
        System.out.println("reconnected finish when send" + " " +
                           (lend - lstart) + "ms");
      }

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -