J2ME最佳实践之联网开发[2]

[入库:2006年2月23日] [更新:2007年3月24日]

本文简介:

public void run() {
    HttpConnection hc = null;
    InputStream input = null;
    try {
        hc = (HttpConnection)Connector.open(url);
        hc.setRequestMethod(HttpConnection.GET); // 默认即为GET
        hc.setRequestProperty("User-Agent", USER_AGENT);
        // get response code:
        int code = hc.getResponseCode();
        if(code!=HttpConnection.HTTP_OK) {
            listener.onError(code, hc.getResponseMessage());
            return;
        }
        // get size:
        int size = (int)hc.getLength(); // 返回响应大小,或者-1如果大小无法确定
        listener.onSetSize(size);
        // 开始读响应:
        input = hc.openInputStream();
        int percent = 0; // percentage
        int tmp_percent = 0;
        int index = 0; // buffer index
        int reads; // each byte
        if(size!=(-1))
            buffer = new byte[size]; // 响应大小已知,确定缓冲区大小
        else
            buffer = new byte[MAX_LENGTH]; // 响应大小未知,设定一个固定大小的缓冲区
        while(!cancel) {
            int len = buffer.length - index;
            len = len>128 ? 128 : len;
            reads = input.read(buffer, index, len);
            if(reads<=0)
                break;
            index += reads;
            if(size>0) { // 更新进度
                tmp_percent = index * 100 / size;
                if(tmp_percent!=percent) {
                    percent = tmp_percent;
                    listener.onProgress(percent);
                }
            }
        }
        if(!cancel && input.available()>0) // 缓冲区已满,无法继续读取
            listener.onError(601, "Buffer overflow.");
        if(!cancel) {
            if(size!=(-1) && index!=size)
                listener.onError(102, "Content-Length does not match.");
            else
                listener.onFinish(buffer, index);
        }
    }
    catch(IOException ioe) {
        listener.onError(101, "IOException: " + ioe.getMessage());
    }
    finally { // 清理资源
        if(input!=null)
            try { input.close(); } catch(IOException ioe) {}
        if(hc!=null)
            try { hc.close(); } catch(IOException ioe) {}
    }
}

本文关键:J2ME最佳实践之联网开发
 

本站最佳浏览方式为 分辨率 1024x768 IE 6.0(或更高版本的 IE浏览器)

go top