📄 httpconnector.java
字号:
package com.gameislive.browser;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;
import wmlcparser.WmlcParser;
public class HttpConnector {
/**
* 是否使用代理
*/
public static boolean isProxy = false;
/**
* WAP网关类型: 0:unknown 1:NOKIA 2:HUAWEI 3:ZET
*/
private static byte gateway = 0;
/**
* 网关类型:其它网关
*/
static final byte GATEWAY_UNKNOWN = 0;
/**
* 网关类型:诺基亚网关 NOKIA
*/
static final byte GATEWAY_NOKIA = 1;
/**
* 网关类型:华为网关 HUAWEI
*/
static final byte GATEWAY_HUAWEI = 2;
/**
* ZET网关
*/
static final byte GATEWAY_ZT3 = 3;
/**
* 是否使用wmlcparser
*/
static boolean usewmlc;
/**
* 最后一次请求时返回的文档类型
*/
static String lastContentType;
/**
* 最后一次请求时返回的cookies
*/
static String lastCookies;
/**
* wmlc解释器,注意不用时清空释放内存
*/
static WmlcParser wmlcParser;
public static void destroy(){
wmlcParser = null;
lastContentType = null;
}
public static byte[] sendHttpRequest(HttpRequest req,
String referer,Browser browser) throws Exception {
if (req == null)
return null;
System.out.println("sendHttpRequest: urlOld=" + req.getUrl());
String destUrl = req.getUrl();
if (destUrl == null || "".equals(destUrl.trim())) {
return null;
}
String method = req.getMethod();
Hashtable headers = req.getHeaders();
byte[] postData = req.getPostData();
HttpConnection conn = null;
InputStream in = null;
int responseCode = -1;
String request;
int index = 0;
byte[] array = null;
lastContentType = null;
lastCookies = null;
try {
String tempStr = destUrl;
String destUrlNoHttp = destUrl;
String suffix = null;
String host = null;
String port = null;
if (tempStr.toLowerCase().startsWith("http://")) {
destUrlNoHttp = tempStr.substring(7);
tempStr = destUrlNoHttp;
}
index = tempStr.indexOf('/');
if (index > 0) {
suffix = tempStr.substring(index);
host = tempStr.substring(0, index);
} else {
suffix = "";
host = tempStr;
}
index = host.indexOf(":");
if (index > -1) {
port = host.substring(index + 1);
host = host.substring(0, index);
}
if (port == null) {
if (host.equals("wap.moffy.com")) {
port = "9080";
} else {
port = "80";
}
}
if (isProxy) { // x-online-host
request = "http://10.0.0.172:80" + suffix;
} else // no proxy
{
request = destUrl;
}
if (GATEWAY_HUAWEI == gateway) {
request = removeHttp(request);
}
if ("POST".equals(method)) {
System.out.println("sendHttpRequest POST \nurl: "+request);
conn = (HttpConnection) Connector.open(request,
Connector.READ_WRITE, true);
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Content-Length",Integer.toString( postData != null?postData.length : 0 ) );
} else {
System.out.println("sendHttpRequest GET \nurl: "+request);
conn = (HttpConnection) Connector.open(request, Connector.READ,
true);
}
conn.setRequestMethod(method);
//conn.setRequestProperty("Connection", "close");
if (headers != null) {
Enumeration e = headers.keys();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = (String) headers.get(key);
conn.setRequestProperty(key, value);
}
}
if (referer != null && !"".equals(referer.trim())) {
conn.setRequestProperty("Referer", referer);
}
if (isProxy) {
conn.setRequestProperty("X-Online-Host", host + ":" + port);
}
if (HttpConnection.POST.equals(method) && postData != null) {
OutputStream outputstream = conn.openOutputStream();
outputstream.write(postData);
//#if (QD || N7610 || N3650 || SE)
//outputstream.flush();
//#endif
outputstream.close();
}
responseCode = conn.getResponseCode();
in = conn.openInputStream();
if (responseCode != HttpConnection.HTTP_OK && responseCode != 302
&& responseCode != 301) {
conn.close();
return new byte[] { -1 };
}
if (responseCode == 302 || responseCode == 301) {
String nextLocation = conn.getHeaderField("Location");
HttpRequest nextRequest = new HttpRequest(browser.getUrl(nextLocation),
HttpConnection.GET, null, req.getHeaders());
return sendHttpRequest(nextRequest, browser.getUrl(req.getUrl()),browser);
}
try{
String tmp = conn.getHeaderField("viagateway");
if(tmp!=null && !tmp.equals("")){
gateway = Byte.parseByte(tmp);
}
}catch(Exception ex){
System.out.println("get header:[viagateway] error!");
ex.printStackTrace();
}
lastContentType = conn.getHeaderField("Content-Type");
if(lastContentType!=null)
{
if(lastContentType.indexOf("application/vnd.wap.wmlc")!=-1){
usewmlc = true;
}
}
lastCookies = conn.getHeaderField("Set-Cookie");
String contentLength = conn.getHeaderField("Content-Length");
// System.out.println("sendHttpRequest() ==> contentLength="
// + contentLength);
int contentLengthInt = -1;
try {
contentLengthInt = Integer.parseInt(contentLength);
} catch (Exception ex) {
contentLengthInt = -1;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (contentLengthInt > 0) {
int b = 0;
for (int i = 0; i < contentLengthInt; i++) {
b = in.read();
// this addition condition is NOT tested!
if (b < 0) {
// error case: actual content is < contentLength
// / contentLengthInt = xxx
break;
}
baos.write(b);
}
// potential addition
// b = -1;
// while ((b = in.read()) != -1) {
// baos.write((byte) (b & 0xff));
// }
} else {
int b = -1;
while ((b = in.read()) != -1) {
baos.write((byte) (b & 0xff));
}
}
// peter: potential faster algorithm for Nokia bug
// byte barray[] = new byte[1000];
// int oneTotal=0, total = 0;
// while (true)
// {
// oneTotal = in.read(barray);
// // wrong: if (oneTotal < 1000) break;
// if (oneTotal < 0) break;
//
// if (oneTotal > 0) {
// baos.write(barray, 0, oneTotal);
// total += oneTotal;
// }
// }
array = baos.toByteArray();
if(usewmlc)
{
if(wmlcParser==null) wmlcParser = new WmlcParser();
String str = wmlcParser.parseWmlc(array);
if(str == null)
{
return new byte[] { -1 };
}
System.out.println("parser.charset == " + wmlcParser.getCharsetStr() );
System.out.println("tag.toString == " + str);
array = str.getBytes(wmlcParser.getCharsetStr());
System.out.println("default charset == " + System.getProperty("microedition.encoding"));
/*array = new WmlcParser().parseWmlc(array).toString().getBytes();*/
}
baos.close();
} catch (Exception e) {
System.out.println("Error occurs in sendHttpRequest "+e.toString());
throw e;
// return new byte[] { -1 };
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
}
}
if (conn != null) {
try {
conn.close();
} catch (Exception e1) {
}
}
}
return array;
}
/**
* 使用华为网关时,去除在URL参数中的"http://"前缀
*/
private static String removeHttp(String url) {
if (url == null) {
return null;
}
String tempUrl = url.toLowerCase();
StringBuffer newUrl = new StringBuffer();
int beginIdx = 0;
int endIdx = tempUrl.indexOf("http://", 1);
while (endIdx > 0) {
newUrl.append(url.substring(beginIdx, endIdx));
beginIdx = endIdx + 7;
endIdx = tempUrl.indexOf("http://", beginIdx);
}
if (beginIdx < url.length()) {
newUrl.append(url.substring(beginIdx));
}
return newUrl.toString();
}
/**
* 获得最后一次请求时的Cookies,如果没有,则返回null
* @return
*/
public static String getLastResponseCookie(){
String session = null;
if(lastCookies!=null){
int n = lastCookies.indexOf(';');
session = lastCookies.substring(0, n);
}
return session;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -