日期:2014-05-20 浏览次数:20914 次
新建一个Midp应用程序,在startApp中加入以下代码:
????? 1 SocketConnection conn = null; 2 OutputStream os = null; 3 InputStream is = null; 4 try { 5 // url: https://ebs.95559.com.cn/corporbank/es_logon.jsp 6 conn = (SocketConnection) Connector.open("socket://10.0.0.172:80", Connector.READ_WRITE, true); 7 conn.setSocketOption(SocketConnection.DELAY, 0); 8 conn.setSocketOption(SocketConnection.KEEPALIVE, 300); 9 10 // 发送和回复的请求 11 os = conn.openDataOutputStream(); 12 is = conn.openDataInputStream(); 13 14 // 在此我们使用HTTP 1.0,HTTP 1.1自己还需要处理chunk,比较麻烦 15 String reqStr = 16 "GET https://ebs.95559.com.cn/corporbank/es_logon.jsp HTTP/1.0\r\n" + 17 "Host: ebs.95559.com.cn:443\r\n" + 18 "User-Agent: FelixBrowser\r\n" + 19 "Accept-Charset: utf-8;\r\n" + 20 "Connection: close;\r\n" + 21 "Accept-Language: zh-cn\r\n\r\n"; 22 23 os.write(reqStr.getBytes()); 24 os.flush(); 25 26 System.out.println("Response Stream:"); 27 byte[] buf = new byte[128]; 28 while (true) { 29 int availSize = is.read(buf, 0, buf.length); 30 if (availSize == -1) { 31 break; 32 } 33 System.out.println(new String(buf, 0, availSize)); 34 } 35 } catch (Exception ex) { 36 ex.printStackTrace(); 37 } finally { 38 if (is != null) { 39 try { 40 is.close(); 41 } catch (IOException ex) { 42 ex.printStackTrace(); 43 } 44 } 45 46 if (os != null) { 47 try { 48 os.close(); 49 } catch (IOException ex) { 50 ex.printStackTrace(); 51 } 52 } 53 54 if (conn != null) { 55 try { 56 conn.close(); 57 } catch (IOException ex) { 58 ex.printStackTrace(); 59 } 60 } 61 } 62 |
输出结果:
OK,这就是我们想要的结果。
封装并重构
平时我们用习惯了HttpConnection,对于使用SocketConnection访问HTTP来说,太多的设置和属性拼凑给编码带来了不少麻烦。在完善J2ME-XHTML浏览器时,我将Socket访问HTTP这一块代码封装成一个类SocketHttpConnection,此类继承自HttpConnection,实现了接口方法。
并且,我还构建了一个工厂类,可以通过枚举的方式创建SocketHttpConnection和纯HttpConnection,有工厂创建的类还可以制定是以代理的方式连接还是直连。在此,我将代码贡献出来给大家。下载地址:这里。
几个类之间的关系如下:
使用方法很简单:
1 // 请求地址 2 String url = "https://ebs.95559.com.cn/corporbank/es_logon.jsp"; 3 4 // 连接方式:SocketConnection/HttpConnection 5 byte connType = HttpConnectionFactory.CONNTYPE_SOCKET_HTTP; 6 7 // 是否使用代理及代理地址、端口 8 boolean isUseProxy = true; 9 String proxyHost = "10.0.0.172"; 10 int proxyPort = 80; 11 12 HttpConnection conn = null; 13 InputStream is = null; 14 try { 15 // 调用工厂创建 16 conn = HttpConnectionFactory.getConnection(url, connType, isUseProxy, proxyHost, proxyPort); 17 18 // 像原生HttpConnection一样使用 19 int code = conn.getResponseCode(); 20 System.out.println("Response Code: " + code); 21 22 is = conn.openDataInputStream(); 23 24 System.out.println("Response Stream:"); 25 byte[] buf = new byte[128]; 26 while (true) { 27 int availSize = is.read(buf, 0, buf.length); 28 System.out.println(new String(buf, 0, availSize)); 29 30 if (availSize < buf.length) { 31 break; 32 } 33 } 34 } catch (IOException ex) { 35 ex.printStackTrace(); 36 } 37 |