日期:2014-05-20  浏览次数:20757 次

高手指点,为何J2ME中通过HttpConnection读取HTML页面在真机上始终无法读取完整的HTML内容?
高手指点,为何J2ME中通过HttpConnection读取HTML页面在真机上始终无法读取完整的HTML内容?
我的代码片段如下: 
public class HtmlGetThread extends ThreadWrapper implements Runnable {

private HttpConnection c = null;
private String url = null;
private Vector listeners = new Vector();

public static final int MAX_LENGTH = 1024;

public HtmlGetThread(String url) {
this.url = url;

}

public String getHtmlViaURL() {
initConnection();
return getHtml();
}

private void initConnection() {
try {
c = (HttpConnection) Connector.open(url);
c.setRequestMethod(HttpConnection.GET);
} catch (IOException e) {
e.printStackTrace();
c = null;
}
}

private String getHtml() {
DataInputStream input = null;
byte[] buffer;
StringBuffer sb = new StringBuffer();
String ret = "";
try {
int code = c.getResponseCode();

if (code != HttpConnection.HTTP_OK) {
// listener.onError(code, hc.getResponseMessage());
return "";
}

input = c.openDataInputStream();

int index = 0; // buffer index
int reads; // each byte

while (true) {
buffer = new byte[MAX_LENGTH];
reads = input.read(buffer, 0, MAX_LENGTH);
if (reads <= 0)
break;

index += reads;
notifyBytesReceived(index);

String s = new String(buffer, "gb2312");
sb.append(s);
}

/*
 * if (input.available() > 0) // 缓冲区已满,无法继续读取 return "";
 */

} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (input != null)
try {
input.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}

return ret;

}

public void run() {
String html = getHtmlViaURL();
HtmlGetEvent e = new HtmlGetEvent(HtmlGetEvent.STATUS_OK, html);
notifyHtmlGet(e);
}

public void addHtmlGetListener(IHtmlGetListener l) {
listeners.addElement(l);
}

public void notifyHtmlGet(HtmlGetEvent e) {
Enumeration enum = listeners.elements();
while (enum.hasMoreElements()) {
Object o = enum.nextElement();
if (o instanceof IHtmlGetListener) {
IHtmlGetListener l = (IHtmlGetListener) o;
l.onHtmlGet(e);
}
}
}

public void notifyBytesReceived(int size) {
Enumeration enum = listeners.elements();
while (enum.hasMoreElements()) {
Object o = enum.nextElement();
if (o instanceof IHtmlGetListener) {
IHtmlGetListener l = (IHtmlGetListener) o;
l.onBytesReceived(size);
}
}
}
}

真机测试发现始终无法完整读取内容。
------最佳解决方案--------------------